【问题标题】:Python: Regex: Detecting hyphenated names and non-hyphenated names with one regexPython:正则表达式:使用一个正则表达式检测连字符名称和非连字符名称
【发布时间】:2015-09-25 14:45:47
【问题描述】:

我需要从一个很长的字符串中提取人名。

他们的名字采用以下格式:LAST,FIRST。

其中一些人的名字带有连字符。有些没有。

我尝试使用较小的字符串:

输入:

import re
text = 'Smith-Jones, Robert&Epson, Robert'
pattern = r'[A-Za-z]+(-[A-Za-z]+)?,\sRobert'
print re.findall(pattern, text)

预期输出:

['Smith-Jones, Robert', 'Epson, Robert']

实际输出:

['-Jones', '']

我做错了什么?

【问题讨论】:

    标签: python regex capturing-group


    【解决方案1】:

    使用

    import re
    text = 'Smith-Jones, Robert&Epson, Robert'
    pattern = r'[A-Za-z]+(?:-[A-Za-z]+)?,\sRobert'
    print re.findall(pattern, text)
    # => ['Smith-Jones, Robert', 'Epson, Robert']
    

    只需使捕获组不捕获即可。问题是findall 如果它们在正则表达式模式中指定,则返回捕获组值。因此,在这种模式下解决此问题的最佳方法是将(...)? 替换为(?:...)?。

    见IDEONE demo

    【讨论】:

    • 万一有条目​​在Robert 之前缺少空格,您可以在\s 之后添加一个* 量词以匹配0 次或更多次出现:r'[A-Za-z]+(?:-[A-Za-z]+)?,\s*Robert'。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 2014-07-28
    • 1970-01-01
    • 2013-02-17
    相关资源
    最近更新 更多