如何解决python正则匹配的懒惰性问题

zhonghuayindi 2011-05-02 02:07:47
import re
cn=lambda x:x.decode("u8")
a=re.findall("\(.*\)",cn("5不去(jmj),了(j大家m你)不"))
for i in a:
print i
运行结果:(jmj),了(j大家m你)
我知道这是正则匹配的懒惰性造成的,那么该怎么修改来避免这一点
从而得到如下的运行结果:
(jmj)
(j大家m你)
...全文
151 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
iambic 2011-05-02
  • 打赏
  • 举报
回复
r'\([^)]*\)'
luotuo512 2011-05-02
  • 打赏
  • 举报
回复
*?, +?, ??
The "*", "+", and "?" qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn't desired; if the RE <.*> is matched against '<H1>title</H1>', it will match the entire string, and not just '<H1>'. Adding "?" after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '<H1>'.
奔跑哥 2011-05-02
  • 打赏
  • 举报
回复
a=re.findall("\(.*?\)",cn("5不去(jmj),了(j大家m你)不"))
zhonghuayindi 2011-05-02
  • 打赏
  • 举报
回复
晕,不会结帖给分…
zhonghuayindi 2011-05-02
  • 打赏
  • 举报
回复
谢谢三位高人!

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧