匹配python中的重复模式

匹配python中的重复模式,python,regex,python-3.x,string,Python,Regex,Python 3.x,String,我试图在python字符串中找到所有遵循特定模式的字符串 "\[\[Cats:.*\]\]" 但是,如果此类模式的多个实例同时存在于字符串中的一行中,则它会将该模式视为一个,而不是单独使用这些模式 strng = '[[Cats: Text1]] said I am in the [[Cats: Text2]]fhg is abnorn' x = re.findall("\[\[Cats:.*\]\]", strng) 得到的输出是: ['[[Cats: Text1]] said I am

我试图在python字符串中找到所有遵循特定模式的字符串

"\[\[Cats:.*\]\]"
但是,如果此类模式的多个实例同时存在于字符串中的一行中,则它会将该模式视为一个,而不是单独使用这些模式

strng = '[[Cats: Text1]] said I am in the [[Cats: Text2]]fhg is abnorn'
x = re.findall("\[\[Cats:.*\]\]", strng) 
得到的输出是:

['[[Cats: Text1]] said I am in the [[Cats: Text2]]']
而不是

['[[Cats: Text1]]', '[[Cats: Text2]]']
这是一个列表列表

我应该使用什么正则表达式?

“\[\[Cats:..*?\]\]”

你当前的正则表达式是贪婪的-它吞噬了一切,从第一个打开的括号到最后一个关闭的括号。使其非贪婪应返回所有结果


问题是您正在进行贪婪的搜索,是否添加?之后。*以获得非贪婪回报

代码如下:

import re

strng = '[[Cats: Text1]] said I am in the [[Cats: Text2]]fhg is abnorn'
regex_template = re.compile(r'\[\[Cats:.*?\]\]') 
matches = re.findall(regex_template, strng)
print(matches)

不要这样做,因为那永远不会结束表示任何字符,甚至不需要出现一次

重新导入
strng='''[[猫:哈哈,这是100%的畏缩]]
说我在[[猫:哈哈,这是100%的畏缩]]
fhg是异常的''
x=re.findall(r“\[\[Cats:[^\]]+\]\]\]”,strng)
打印(x)

“\[\[Cats:..\]\]”
如果括号内的字符串包含一个右括号,请尝试
\[\[Cats:....\]\]\]
正则表达式失败。同样误导的是,
*
“终止”很好。