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

标签 python regex

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

这里有一些例子:

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}' 将匹配第一个,也可以匹配第二个,如果它们是大写的话。

关于Python 正则表达式提取第一个大写单词或第一个和第二个单词(如果两者都大写),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44960996/

相关文章:

regex - 下划线转换为驼峰式正则表达式

javascript - 用 RegEx 替换文本

JavaScript 日期时间格式验证正则表达式 [dd-mm-yyyy hh :mm]

python - 如何与通配符合并? - Pandas

python - 为什么我得到的是 sqlalchemy.exc.ProgrammingError 而不是 sqlalchemy.exc.IntegrityError?

python - 将独立的Python应用程序分发到其他机器

java - 我在 Pattern.compile() 和 .matcher() 中传递变量,但没有获得所需的输出

python - 如何在 plotly (python) sankey 中显示图例?

python - 在 Python 中关闭文件

python - 用生成的图像替换 xml 标签(python 正则表达式)