17
>>> import re
>>> s = 'this is a test'
>>> reg1 = re.compile('test$')
>>> match1 = reg1.match(s)
>>> print match1
None

在与 s 结尾处的测试相匹配的 Kiki 中。我想念什么?(我也试过re.compile(r'test$')

4

3 回答 3

33

利用

match1 = reg1.search(s)

反而。该match函数在字符串的开头匹配...请参阅此处的文档:

Python 基于正则表达式提供了两种不同的原始操作:re.match()仅在字符串的开头检查匹配,而在re.search()字符串中的任何位置检查匹配(这是 Perl 默认所做的)。

于 2012-10-22T15:27:54.610 回答
1

您的正则表达式与完整字符串不匹配。您可以使用搜索来代替无用提到的,或者您可以更改您的正则表达式以匹配完整的字符串:

'^this is a test$'

或者有点难以阅读但没那么无用:

'^t[^t]*test$'

这取决于你想要做什么。

于 2012-10-22T15:31:35.923 回答
0

这是因为如果找不到预期的模式,该match方法会返回,如果找到模式,它将返回一个类型为.None_sre.SRE_match

所以,如果你想得到布尔(TrueFalse)结果,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!")
于 2019-11-30T20:40:10.343 回答