Regex-match不返回任何值。我错在哪里?

2024-06-16 11:36:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

在琪琪,和s结束时的测试吻合。我错过了什么?(我也试过re.compile(r'test$')


Tags: testimportrenoneismatchthisprint
3条回答

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

'^this is a test$'

或者读起来有点难,但没那么没用:

'^t[^t]*test$'

这取决于你想做什么。

使用

match1 = reg1.search(s)

相反。match函数只在字符串开头匹配。。。请参阅文档here

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).

因为match方法返回None如果它找不到预期的模式,如果它找到模式,它将返回类型为_sre.SRE_match的对象。

所以,如果你想从match得到布尔值(TrueFalse),你必须检查结果是否是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!")

相关问题 更多 >