我想匹配字符串中的可能名称。名称应为2-4个单词,每个单词包含3个或更多字母,所有单词均为大写。例如,给定这个字符串列表:
Her name is Emily.
I work for Surya Soft.
I sent an email for Ery Wulandari.
Welcome to the Link Building Partner program!
我想要一个返回的正则表达式:
None
Surya Soft
Ery Wulandari
Link Building Partner
目前这是我的代码:
data = [
'Her name is Emily.',
'I work for Surya Soft.',
'I sent an email for Ery Wulandari.',
'Welcome to the Link Building Partner program!'
]
for line in data:
print re.findall('(?:[A-Z][a-z0-9]{2,}\s+[A-Z][a-z0-9]{2,})', line)
它适用于前三行,但在最后一行失败。
答案 0 :(得分:2)
您可以使用:
re.findall(r'((?:[A-Z]\w{2,}\s*){2,4})', line)
它可能会添加一个可以使用.strip()
答案 1 :(得分:2)
您可以使用分组重复结构,如下所示:
compiled = re.compile('(?:(([A-Z][a-z0-9]{2,})\s*){2,})')
for line in data:
match = compiled.search(line)
if match:
print match.group()
else:
print None
输出:
None
Surya Soft
Ery Wulandari
Link Building Partner
答案 2 :(得分:1)
非正则表达式解决方案:
from string import punctuation as punc
def solve(strs):
words = [[]]
for i,x in enumerate(strs.split()):
x = x.strip(punc)
if x[0].isupper() and len(x)>2:
if words[-1] and words[-1][-1][0] == i-1:
words[-1].append((i,x))
else:
words.append([(i,x)])
names = [" ".join(y[1] for y in x) for x in words if 2 <= len(x) <= 4]
return ", ".join(names) if names else None
data = [
'Her name is Emily.',
'I work for Surya Soft.',
'I sent an email for Ery Wulandari.',
'Welcome to the Link Building Partner abc Fooo Foo program!'
]
for x in data:
print solve(x)
<强>输出:强>
None
Surya Soft
Ery Wulandari
Link Building Partner, Fooo Foo
答案 3 :(得分:0)
for line in data:
print re.findall("[A-Z][\w]+", line)