>>> import re
>>> s = 'this is a test'
>>> reg1 = re.compile('test$')
>>> match1 = reg1.match(s)
>>> print match1
None
在与 s 结尾处的测试相匹配的 Kiki 中。我想念什么?(我也试过re.compile(r'test$')
)
利用
match1 = reg1.search(s)
反而。该match
函数仅在字符串的开头匹配...请参阅此处的文档:
Python 基于正则表达式提供了两种不同的原始操作:
re.match()
仅在字符串的开头检查匹配,而在re.search()
字符串中的任何位置检查匹配(这是 Perl 默认所做的)。
您的正则表达式与完整字符串不匹配。您可以使用搜索来代替无用提到的,或者您可以更改您的正则表达式以匹配完整的字符串:
'^this is a test$'
或者有点难以阅读但没那么无用:
'^t[^t]*test$'
这取决于你想要做什么。
这是因为如果找不到预期的模式,该match
方法会返回,如果找到模式,它将返回一个类型为.None
_sre.SRE_match
所以,如果你想得到布尔(True
或False
)结果,match
你必须检查结果是否None
!
您可以像这样检查文本是否匹配:
string_to_evaluate = "Your text that needs to be examined"
expected_pattern = "pattern"
if re.match(expected_pattern, string_to_evaluate) is not None:
print("The text is as you expected!")
else:
print("The text is not as you expected!")