python 贪婪和非贪婪模式

这样的正则表达式:

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>

  

原文地址:https://www.cnblogs.com/ldphoebe/p/5564569.html