首页 > 编程语言 > 详细

python 贪婪和非贪婪模式

时间:2016-06-06 18:38:24      阅读:228      评论:0      收藏:0      [点我收藏+]

这样的正则表达式:

r‘\*(.+)\*‘  如果想要匹配*something*这样的一个串按道理说是没问题的

但是如果文本是*this* is *something*

那么我们的正则表达式就会采取贪婪模式匹配第一个* 最后一个*

而中间的 两个*就当作是第一个分组里面的内容了

要想采取非贪婪模式 就只需在其后面加一个问号r‘\*(.+?)\*‘

s1=‘hello,*something!*

pattern1=re.compile(‘\*(.+)\*‘)
print re.sub(pattern1,r‘<em>\1</em>‘,s1)
##输出结果hello,<em>something</em>
#############################################


s = ‘*hello* is *something*‘

pattern =re.compile(r‘\*(.+)\*‘)
print re.sub(pattern, r‘<em>\1<em>‘, s)

#输出结果
<em>hello* is *something<em>
#############################################
s = ‘*hello* is *something*‘

pattern =re.compile(r‘\*(.+?)\*‘)
print re.sub(pattern, r‘<em>\1<em>‘, s)

#输出结果<em>hello<em> is <em>something<em>

  

python 贪婪和非贪婪模式

原文:http://www.cnblogs.com/ldphoebe/p/5564569.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!