【发布时间】:2012-10-22 15:25:59
【问题描述】:
>>> import re
>>> s = 'this is a test'
>>> reg1 = re.compile('test$')
>>> match1 = reg1.match(s)
>>> print match1
None
在与 s 末尾的测试匹配的 Kiki 中。我想念什么? (我也试过re.compile(r'test$'))
【问题讨论】:
>>> 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 函数 only 匹配字符串的开头...参见文档here:
Python 提供了两种基于正则表达式的不同原始操作:
re.match()仅在字符串的开头检查匹配,而re.search()在字符串中的任何位置检查匹配(这是 Perl 默认所做的) .
【讨论】:
您的正则表达式不匹配完整的字符串。您可以使用 search 来代替 Useless 提到的,或者您可以更改您的正则表达式以匹配完整的字符串:
'^this is a test$'
或者有些难以阅读,但没那么无用:
'^t[^t]*test$'
这取决于你想要做什么。
【讨论】:
这是因为 match 方法如果找不到预期的模式,则返回 None,如果找到模式,它将返回一个类型为 _sre.SRE_match 的对象。
因此,如果您想要来自 match 的布尔(True 或 False)结果,您必须检查结果是否为 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!")
【讨论】: