例如,我有一个像 '(10 + 20)/(10 + 20)' 这样的字符串。
现在我想匹配 (10 + 20)。所以我写了一个这样的脚本:
text = '(10 + 20) / (10 + 20)'
test1 = re.findall(r'(.*)', text)
test2 = re.findall(r'(.+?)', text)
for i in test1:
print(i, end='')
else:
print()
for i in test2:
print(i, end='')
else:
print()
输出是这样的:
(10 + 20) / (10 + 20)
(10 + 20) / (10 + 20)
我不明白,.+?不贪心吗?
请您参考如下方法:
正则表达式模式中的圆括号必须使用 \ 进行转义匹配文字圆括号:
test2 = re.findall(r'\(.+?\)', text)
参见 demo
“原始”字符串文字并不意味着您不必转义特殊的正则表达式字符,而是意味着您可以只使用一个反斜杠来转义它们,而不是两个。
请参阅 6.2.5.8. Raw String Notation 中的这段摘录:
Raw string notation
(r"text")keeps regular expressions sane. Without it, every backslash ('\') in a regular expression would have to be prefixed with another one to escape it. For example, the two following lines of code are functionally identical:
>>>
>>> re.match(r"\W(.)\1\W", " ff ")
<_sre.SRE_Match object; span=(0, 4), match=' ff '>
>>> re.match("\\W(.)\\1\\W", " ff ")
<_sre.SRE_Match object; span=(0, 4), match=' ff '>
文档说通常,但这并不意味着您每次都必须使用原始字符串文字。
.+? 是真的是惰性模式,它意味着匹配除换行符以外的 1 个或多个字符,但尽可能少。
