贪婪模式也就是我们使用 .* 匹配任意字符时会尽可能长地向后匹配,如果我们想阻止这种贪婪模式,需要加个问号,尽可能少地匹配,如下例子:
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>']
实例:使用非贪婪模式匹配 /var/log/messages 日志
[root@localhost ~]$ tail /var/log/messages Jan 25 13:42:13 localhost dhclient[972]: DHCPREQUEST on eth0 to 192.168.216.254 port 67 (xid=0xa32724e) Jan 25 13:42:13 localhost dhclient[972]: DHCPACK from 192.168.216.254 (xid=0xa32724e) Jan 25 13:42:15 localhost dhclient[972]: bound to 192.168.216.128 -- renewal in 882 seconds.