[英]Trying to understand Mathematica's code and replicate in Python
[英]Trying to understand Python Regex's
我正在尝试编写一个 Python 正则表达式来捕获姓氏为 Nakamoto 的人的全名? 您可以假设出现在它之前的名字始终是一个以大写字母开头的单词。 正则表达式必须符合以下条件:
'Satoshi Nakamoto'
'Alice Nakamoto'
'RoboCop Nakamoto'
但不是以下内容:
'satoshi Nakamoto' (where the first name is not capitalised)
'Mr. Nakamoto' (where the preceding word has a nonletter character)
'Nakamoto' (which has no first name)
'Satoshi nakamoto' (where Nakamoto is not capitalised)
我使用了以下正则表达式: [AZ][az]+\\sNakamoto
然而,这同时捕获了中Satoshi Nakamoto
和中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())
re.I
表示忽略大小写,因此您使用的显式大写类无论如何都会匹配大写和小写。 不要使用re.I
。 此外,要匹配“RoboCop”,您需要在一个名称中接受多个大写字母,因此您可能需要:
NameSearch = re.compile(r'\b[A-Z][a-zA-Z]+\sNakamoto\b', re.VERBOSE)
或类似。 这也使用\\b
作为单词边界检测器,因此您不会在像fooBar Nakamoto
这样的字符串中途匹配。
您的正则表达式实际上在这里工作正常,但它与“RoboCop Nakamoto”情况不符。
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')
输出是这样的:
"test satoshi Nakamoto test" does not match
"test Satoshi Nakamoto test" matches
"test RoboCop Nakamoto test" matches
"test roboCop Nakamoto test" does not match
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.