Python正则表达式为什么量词(+)不贪婪

问题描述 投票:-1回答:1

输入:asjkd http://www.as.com/as/g/ff askl

预期输出:http://www.as.com/as/g/ff

当我尝试以下操作时,我将获得预期的输出

pattern=re.compile(r'http[\w./:]+')
print(pattern.search("asjkd http://www.as.com/as/g/ff askl"))

为什么+量词在这里不贪婪?我原以为它会很贪心。在这里实际上不贪心有助于找到正确的答案。

python regex
1个回答
0
投票

贪婪。当碰到空格时,它将停止匹配,因为[\w./:]与空格不匹配。空格不是word character(字母数字或下划线),点,斜杠或冒号。

+更改为+?,可以看到当它不是贪婪时会发生什么。

Greedy

>>> pattern=re.compile(r'http[\w./:]+')
>>> print(pattern.search("asjkd http://www.as.com/as/g/ff askl"))
<re.Match object; span=(6, 31), match='http://www.as.com/as/g/ff'>

非贪婪

>>> pattern=re.compile(r'http[\w./:]+?')
>>> print(pattern.search("asjkd http://www.as.com/as/g/ff askl"))
<re.Match object; span=(6, 11), match='http:'>

与单个字符:匹配!

© www.soinside.com 2019 - 2024. All rights reserved.