gpt4 book ai didi

python - `re` 模块匹配Python3中两对括号之间的文本

转载 作者:太空宇宙 更新时间:2023-11-04 08:53:38 24 4
gpt4 key购买 nike

例如,我有一个像 '(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 个或多个字符,但尽可能少

关于python - `re` 模块匹配Python3中两对括号之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32604631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com