我正试图编写一个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())
您的正则表达式实际上在这里工作得很好,但它与“robocopnakamoto”的情况不匹配。在
输出如下:
^{pr2}$re.I
表示忽略大小写,因此您使用的显式大写类无论如何都将匹配大写和小写。不要使用re.I
。此外,要匹配“RoboCop”,您需要在一个名称中接受多个大写字母,因此您可能希望:或者类似的。这还使用
\b
作为单词边界检测器,这样就不会在fooBar Nakamoto
这样的字符串中进行部分匹配。在为我工作的那个:
您可以在这里查看:https://regex101.com/r/lNE320/1
相关问题 更多 >
编程相关推荐