Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default).
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!")
正则表达式与完整字符串不匹配。您可以使用search代替前面提到的无用搜索,也可以更改regex以匹配完整字符串:
或者读起来有点难,但没那么没用:
这取决于你想做什么。
使用
相反。
match
函数只在字符串开头匹配。。。请参阅文档here:因为
match
方法返回None
如果它找不到预期的模式,如果它找到模式,它将返回类型为_sre.SRE_match
的对象。所以,如果你想从
match
得到布尔值(True
或False
),你必须检查结果是否是None
!你可以检查文本是否匹配如下:
相关问题 更多 >
编程相关推荐