<p>您可以使用regex <code>^(.*[AaIiUuEeOo])(?=.*[AaIiUuEeOo])(.+)$</code>。我们的想法是捕捉到一个元音的所有内容,然后是另一个元音,还可以选择一些其他字符,这些字符将被放置在第二个捕捉组中。你知道吗</p>
<pre><code>>>> import re
>>> pattern = r"^(.*[AaIiUuEeOo])(?=.*[AaIiUuEeOo])(.+)$"
>>> re.match(pattern, "Describe").groups()
('Descri', 'be')
>>> re.match(pattern, "Public").groups()
('Pu', 'blic')
>>> re.match(pattern, "ibe").groups()
('i', 'be')
>>> re.match(pattern, "ie").groups()
('i', 'e')
</code></pre>
<p>如果字符串至少没有两个元音,请确保在调用结果<code>groups()</code>之前测试<code>None</code>。你知道吗</p>
<p>另一个想法是使用<a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow noreferrer">^{<cd4>}</a>,它比较笨重,但很有趣,可以很好地推广到任何<code>n</code>或任何字符集(或iterables,就这一点而言,我坚持使用字符串)。你知道吗</p>
<pre><code>from itertools import groupby
def nth_from_rear(s, n=2, matches="aeiou"):
def nth_counter(n=2, count=0):
def cb(x):
nonlocal count
if x.lower() in matches:
count += 1
return count >= n
return cb
groups = groupby(s[::-1], key=nth_counter(n))
return ["".join(x)[::-1] for _, x in groups][::-1]
if __name__ == "__main__":
tests = [
["Public", 2],
["Describe", 2],
["ie", 2],
["ibbe", 2],
["Describe", 0],
["Describing", 1],
["Describe", 3],
["ababbaba", 4],
]
for s, n in tests:
print(s.rjust(10), n, nth_from_rear(s, n))
</code></pre>
<p>输出:</p>
<pre class="lang-none prettyprint-override"><code> Public 2 ['Pu', 'blic']
Describe 2 ['Descri', 'be']
ie 2 ['i', 'e']
ibbe 2 ['i', 'bbe']
Describe 0 ['Describe']
Describing 1 ['Describi', 'ng']
Describe 3 ['De', 'scribe']
ababbaba 4 ['a', 'babbaba']
</code></pre>