如何将{}与findall+Python一起使用regex模式

2024-05-04 23:21:55 发布

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

我正在创建一个regex,如下所示:

import re
asd = re.compile(r"(blah){2}")
mo = asd.search("blahblahblahblahblahblah ll2l 21HeHeHeHeHeHe lllo")
mo1 = asd.findall("blahblahblahblahblahblah")
print(mo.group())
print("findall output: ", mo1)

这将返回输出 布拉布拉 findall输出:['blah','blah','blah']

-为什么findall输出与'blah'匹配三次,而它在模式中只指定了{2}次?

如果我改为{4},那么findall匹配:

^{pr2}$

{m}如何处理{m}搜索以及关于芬德尔?

非常感谢。在


Tags: importresearchgroupregexmoblahprint
2条回答

如果您想捕获(blah){2}(其中的2blah),您应该包装它:

asd = re.compile(r"((?:blah){2})")

Note that I made sure not to catch the inside blah (using ?:)

^{pr2}$

你现在的{4}也一样。regex会找到它,但不会捕捉到它。如果你想抓住它,你应该把它包起来。在

(blah){2}捕获并耗尽字符串blahblah,但只返回blahblah中的最后一个blah。由于字符串中有三个blahblah,它将输出['blah', 'blah', 'blah']

(blah){4}只能匹配一次,因此它给您['blah']

相关问题 更多 >