Python:正则表达式:使用一个正则表达式检测带连字符的名称和非带连字符的名称

Python: Regex: Detecting hyphenated names and non-hyphenated names with one regex

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

他们的名字采用以下格式: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', '']

我做错了什么?

使用

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 returns 捕获在正则表达式模式中指定的组值。因此,在此模式中解决此问题的最佳方法是将 (...)? 替换为 (?:...)?.

IDEONE demo