试图理解Python正则表达式

2024-09-30 23:33:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图编写一个Python正则表达式来捕获姓氏为Nakamoto的人的全名?你可以假设前面的名字总是一个以大写字母开头的单词。正则表达式必须匹配以下内容:

'Satoshi Nakamoto'
'Alice Nakamoto'
'RoboCop Nakamoto'

但不包括以下内容:

^{pr2}$

我使用了以下regex:[A-Z][a-z]+\sNakamoto

但是,这将同时捕获Satoshi Nakamoto和{}。我想知道我错在哪里,如何改正。这是我的代码:

import re    #import regular expressions

#regular expression
NameSearch = re.compile(r'[A-Z][a-z]+\sNakamoto', re.I | re.VERBOSE)

# perform search on string
Result = NameSearch.search("Satoshi Nakamoto")

#Debug code to check if it found a match or not
print (Result == None)

if Result != None:
    print (Result.group())

Tags: importrenonesearchifresult名字print
3条回答

您的正则表达式实际上在这里工作得很好,但它与“robocopnakamoto”的情况不匹配。在

import re

def printMatch(name):
    pat = re.compile(r'\b[A-Z][a-zA-Z]+\sNakamoto')
    if pat.search(name):
        print '"'+name+'" matches'
    else:
        print '"'+name+'" does not match'

printMatch('test satoshi Nakamoto test')
printMatch('test Satoshi Nakamoto test')
printMatch('test RoboCop Nakamoto test')
printMatch('test roboCop Nakamoto test')

输出如下:

^{pr2}$

re.I表示忽略大小写,因此您使用的显式大写类无论如何都将匹配大写和小写。不要使用re.I。此外,要匹配“RoboCop”,您需要在一个名称中接受多个大写字母,因此您可能希望:

NameSearch = re.compile(r'\b[A-Z][a-zA-Z]+\sNakamoto\b', re.VERBOSE)

或者类似的。这还使用\b作为单词边界检测器,这样就不会在fooBar Nakamoto这样的字符串中进行部分匹配。在

为我工作的那个:

rgx = re.compile(r'^[A-Z]\w+ Nakamoto')

您可以在这里查看:https://regex101.com/r/lNE320/1

相关问题 更多 >