首页 文章

如果两者都大写的话,Python正则表达式会首先使用大写单词或第一和第二单词

提问于
浏览
3

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

这里有些例子:

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)

2 回答

  • 3

    正则表达式是矫枉过正 . 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}' 将匹配第一个,可选第二个,如果它们是大写的 .

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

相关问题