匹配字符串的每个单词中的第一个元音并用正则表达式以逗号分隔打印它们?

match first vowel in each word of a string and print them comma-separated with regex?

这是我目前所拥有的

my_str = "The sky's the limit"

regex = re.findall(r"\b\w*?[aeiouAEIOU]", my_str)
joined_str = ", ".join(regex)

print(joined_str)

我想要打印出来

e, e, i

但它打印

The, the, li

那么如何忽略带有元音的单词的前一个字符,只打印每个单词的第一个元音并用逗号分隔元音?

您只需要限制您想要 returned 的表达式部分,方法是将其封装在捕获组中:

>>> re.findall(r"\b\w*?([aeiouAEIOU])", my_str)
['e', 'e', 'i']

() 告诉正则表达式引擎仅 return 匹配 ().

中的表达式

如果你可以不用正则表达式,你也可以这样做,就像这样:

def find_first_vowel(s):
    first_vowels = ''
    for word in s.split():        
        for index, char in enumerate(word):            
            if char in 'aeiouAEIOU':    # you can check the index here                
                first_vowels += char                
                break
    return ', '.join(first_vowels)

my_str = "The sky's the limit"

>>> print(find_first_vowel(my_str))
e, e, i