非贪婪的正则表达式

时间:2021-07-09 20:59:33

标签: regex

所以我有以下...

temp = 'item 8 but i want this item 8 and Financial Statements and Supplementary Data'
pattern_8  = r'ITEM 8.*?Financial Statements and Supplementary Data'

那我做...

re.search(pattern_8,temp,re.IGNORECASE)
<re.Match object; span=(0, 77), match='item 8 but i want this item 8 and Financial State>

但对我来说,它需要第一个“项目 8”而不是第二个。 我想我可以循环搜索直到它停止..但是这种非贪婪匹配不起作用一定是有原因的吗?

2 个答案:

答案 0 :(得分:1)

您的结果在意料之中。我想你误解了非贪婪的意思。我不是的意思是»使整个正则表达式匹配最短的字符串«,但只是. after {{1} } 尽可能少地匹配,直到遇到 item 8。这可确保您选择第一个 Financial ...,但确保您选择最后一个 Financial ...

搜索 item 8 的起点不受 Financial ... 修饰符的影响。您可以说 ? 是贪婪的,因为只要后面有 item 8,它就会匹配字符串中的第一个 item 8

要获得最短匹配,您可以确保 Financial ... 永远不会出现在 item 8 的匹配部分内。

.*?

答案 1 :(得分:0)

Python 中最新的正则表达式包(不是 re)有一个重叠选项,所以我可以这样做...

import regex as re
re.findall(pattern_8, temp, re.IGNORECASE, overlapped=True)
[(m.start(0), m.end(0)) for m in re.finditer(pattern_8, temp,re.IGNORECASE, overlapped=True)]
Out[161]: [(0, 77), (23, 77)]

使用重叠函数可以让我很快找到两个匹配项。