所以我有以下几点……
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>但对我来说,它需要第一个“第八项”,而不是第二个。我想我可以循环搜索,直到它停止..但这种非贪婪匹配不起作用肯定有原因吧?
发布于 2021-07-10 05:29:29
你的结果是意料之中的。我想你误解了非贪婪的意思。我的意思不是»让整个正则表达式匹配最短的字符串«,而是尽可能少地匹配item 8之后的.,直到遇到Financial ...。这可确保选择第一个Financial ...,但不能确保选择最后一个item 8。
搜索Financial ...的起点不受?修改器的影响。您可以说item 8是贪婪的,因为它将匹配字符串中的第一个item 8,只要在那之后有一个Financial ...。
要获得最短的匹配,您可以确保item 8永远不会出现在.*?的匹配部分中。
item 8((?!item 8).)*?Financial Statements and Supplementary Data发布于 2021-07-10 05:30:56
Python中最新的regex包(不是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)]使用重叠函数可以让我非常快速地完成两个匹配。
https://stackoverflow.com/questions/68322646
复制相似问题