Python字符串必须匹配regex的开头,但不能匹配end

2024-09-27 23:21:08 发布

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

我觉得这种行为有点奇怪:

pattern = re.compile(r"test")
print pattern.match("testsda") is not None
True
print pattern.match("astest") is not None
False

所以,当字符串与末端的模式不匹配时,一切正常。但是当字符串在开始时与模式不匹配时,字符串就不再与模式匹配。你知道吗

相比之下,grep在这两种情况下都取得了成功:

echo "testsda" | grep  test
testsda
echo "adtest" | grep  test
adtest

你知道为什么会这样吗?你知道吗


Tags: 字符串testechorenoneismatch模式
1条回答
网友
1楼 · 发布于 2024-09-27 23:21:08

re.match设计为只在字符串开头匹配。作为docs状态:

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

如果您使用re.search,您应该可以:

import re

pattern = re.compile(r"test")
print pattern.search("testsda") is not None
print pattern.search("astest") is not None

印刷品

True
True

相关问题 更多 >

    热门问题