>>> import re
>>> p = re.compile('.*&l=(.*)(&|$)')
>>> p.search('foo&l=something here&bleh').group(1)
'something here&bleh' # want to remove strings after &
>>> p.search('foo&l=something here').group(1)
'something here' # this is OK
python 文档 (2.7) 说 or 运算符 '|'永远不会贪婪。但是我的代码运行不正常。我希望正则表达式在到达下一个时停止搜索,而不是遍历整个字符串。
请您参考如下方法:
您需要将第一个捕获组中的 .* 更改为 [^&]*
p = re.compile('.*&l=([^&]*)')
您的正则表达式 p = re.compile('.*&l=(.*)(&|$)') 也匹配额外的字符,因为 .* 里面第一个捕获组是贪婪的,它匹配所有字符直到最后一个。大家都知道 $ 匹配最后存在的边界。因此找到一个匹配项。
所以 .* 和 $ 找到一个匹配项,所以它不会得到 backtarck。
