Python 正则表达式拉取第一个大写的单词或第一个和第二个单词(如果两者都大写)



我实现的当前正则表达式公式只能提取给定字符串的前两个大写单词。如果第二个单词未大写,我希望能够只提取字符串中的第一个单词。

以下是一些示例:

s = 'Smith John went to ss for Jones.'
s = 'Jones, Greg went to 2b for Smith.'
s = 'Doe went to ss for Jones.'

本质上,我只想让正则表达式输出以下内容:

'Smith John'
'Jones, Greg'
'Doe'

我拥有的当前正则表达式公式如下,除了它不会捕获 Doe 示例:

new = re.findall(r'([A-Z][w-]*(?:s+[A-Z][w-]*)+)', s)

正则表达式是矫枉过正的。str.isupper()效果很好:

In [11]: def getName(s):
...:     first, second = s.split()[:2]
...:     if first[0].isupper():
...:         if second[0].isupper():
...:             return ' '.join([first, second])
...:         return first
...:     

这给出了:

In [12]: getName('Smith John went to ss for Jones.')
Out[12]: 'Smith John'
In [13]: getName('Jones, Greg went to 2b for Smith.')
Out[13]: 'Jones, Greg'
In [14]: getName('Doe went to ss for Jones.')
Out[14]: 'Doe'

添加一些检查,以便在字符串只有一个单词时不会出错,并且您很高兴。


如果你执意使用正则表达式,你可以使用这样的模式:

In [36]: pattern = re.compile(r'([A-Z].*? ){1,2}')
In [37]: pattern.match('Smith John went to ss for Jones.').group(0).rstrip()
Out[37]: 'Smith John'
In [38]: pattern.match('Doe went to ss for Jones.').group(0).rstrip()
Out[38]: 'Doe'

r'([A-Z].*? ){1,2}'将匹配第一个,如果它们是大写的,则可以选择第二个。

import re
print re.match(r'([A-Z].*?(?:[, ]+)){1,}',s).group()

最新更新