非贪婪的通配符似乎贪婪地匹配?

Non-greedy wild card appears to match greedily?

我需要理解为什么当我指定正则表达式不匹配时它会贪婪地匹配。

给定 string='.GATA..GATA..ETS..ETS.'

Return GATA...ETS的最短子串

我使用正则表达式模式pattern = r'(GATA).*?(ETS)'

syntax_finder=re.compile(pattern,re.IGNORECASE)

for match in syntax_finder.finditer(string):
    print(match)

Returns <re.Match object; span=(1, 17), match='GATA..GATA..ETS'>

不过,我想要它 return 'GATA..ETS'

有人知道为什么会这样吗?

我不是在寻找这个精确匹配问题的解决方案。我将使用更复杂的 GATA 和 ETS 模式进行大量此类搜索,但我始终希望它 return 最短匹配。

谢谢!

Does anyone know why this is happening?

正则表达式非贪婪匹配。它找到第一个 GATA 然后,因为使用 .*? 而不是 .*,匹配直到 first ETS 之后。恰好还有另一个 GATA 挡在了你不想要的地方 - 但哪个非贪婪匹配并不关心。

I will be doing a lot of these types of searches with more complicated patterns of GATA and ETS

那么正则表达式可能无法胜任这项工作。我的建议是使用它们将字符串拆分为 GATA、ETS 和中间部分 (tokenization),然后使用其他技术找到该序列中的模式 (parsing ).

I am not looking for a solution to this exact matching problem.

但我无法抗拒:)

>>> re.search(r'(GATA)((?<!GAT)A|[^A])*?(ETS)', '.GATA..GATA..ETS..ETS.')
<_sre.SRE_Match object; span=(7, 16), match='GATA..ETS'>

这里我们使用了一个否定的lookbehind断言:在扫描GATAETS之间的部分时,如果A前面没有GAT,我们只允许A .