我运行了以下代码,只得到第一个')'作为匹配.有人可以帮我解释为什么常规的贪婪'))'没有被退回?
r=re.compile('\)')
var=r.search('- hi- ))there')
print var.group()
Run Code Online (Sandbox Code Playgroud)
search 只会返回第一场比赛.
要查找所有的匹配使用findall:
r=re.compile('\)')
var= r.findall('- hi- )) there')
print (var)
Run Code Online (Sandbox Code Playgroud)
如果你想在一场比赛中找到两个大括号,请使用:
r=re.compile('\)+')
Run Code Online (Sandbox Code Playgroud)
的+1或多个对象的匹配.
你的正则表达并不贪心.实际上,它的设置只匹配一个字符.如果您希望它也匹配重复,请添加+:
>>> r=re.compile('\)+')
>>> var=r.search('- hi- ))there')
>>> print var.group()
))
Run Code Online (Sandbox Code Playgroud)