Python 正则表达式贪婪模式

贪婪模式也就是我们使用 .* 匹配任意字符时会尽可能长地向后匹配,如果我们想阻止这种贪婪模式,需要加个问号,尽可能少地匹配,如下例子:

In [1]: import re

In [2]: html = '<h1> hello world </h1>'    

In [3]: re.findall(r'<.*>', html)    # 贪婪模式默认匹配到所有内容
Out[3]: ['<h1> hello world </h1>']

In [4]: re.findall(r'<.*?>', html)   # 我们只想匹配两个标签的内容,可以加上问号来阻止贪婪模式
Out[4]: ['<h1>', '</h1>']

    

原文地址:https://www.cnblogs.com/pzk7788/p/10322492.html