python regex:Consider 行尾作为搜索中的 OR 条件,类似于字符 class 中的字符

python regex:Consider end of line as an OR condition in a search, similar to characters in character class

问题: 找出夹在两个辅音之间的所有元音(超过 2 个)。这些元音可以出现在行首或行尾。 示例:-

输入:-

abaabaabaabaae

预期输出:-

['aa','aa','aa','aae']

解决方案已尝试

import re
pattern=re.compile(r'(?:[^aeiouAEIOU])([AEIOUaeiou]{2,})(?=[^AEIOUaeiou])')
pattern.findall("abaabaabaabaae")

这将输出为 ['aa','aa','aa'] ,它会忽略 'aae' ,原因很明显,因为行尾不是搜索条件的一部分。如何包含锚点 - 行尾 ($) 包含搜索,以便它 ($) 是搜索中的 OR 条件,而不是强制性的行尾。

我会使用 re.findall 和模式 (?<=[^\Waeiou])[aeiou]+(?![aeiou]):

inp = "abaabaabaabaae"
matches = re.findall(r'(?<=[^\Waeiou])[aeiou]+(?![aeiou])', inp, flags=re.IGNORECASE)
print(matches)

这会打印:

['aa', 'aa', 'aa', 'aae']

下面是对正则表达式模式的解释:

(?<=[^\Waeiou])  assert that what precedes is any word character, excluding a vowel
                 this also exlcudes the start of the input
[aeiou]+         match one or more vowel characters
(?![aeiou])      assert that what follows is not a vowel (includes end of string)

您可以提取正则表达式的匹配项

re'(?<=[b-df-hj-np-tv-z])[aeiou]{2,}(?=[b-df-hj-np-tv-z]|$)'

Demo

对于以下字符串,指出了匹配项。

_abaab_aabaabaaeraaa_babaa%abaa
   ^^     ^^ ^^^             ^^

我发现最容易将辅音与字符 class

显式匹配
[b-df-hj-np-tv-z]

Python demo