Skip to main content
 首页 » 编程设计

python之正则表达式 : How to filter for two things at once

2025年05月04日24EasonJim

我想要一个正则表达式来返回列表中仅包含辅音而不包含特殊字符的所有单词。

以下 Python 代码有效:

import re 
 
words = ["xkcd", "word", "xml-"] 
consonants_only = [x for x in words 
                      if (re.search("^[^aeiou]+$", x) 
                        and re.search("^[a-z]+$", x))] 
 
print consonants_only 

这会准确返回 ['xkcd']

我的问题是:这可以用一个正则表达式很好地完成吗?我正在寻找的是同时过滤 [^aeiou] 和 [a-z] 的通用方法。

请您参考如下方法:

嗯,你事先知道所有的辅音:

>>> import re 
>>> words = ["xkcd", "word", "xml-"] 
>>> pattern = re.compile(r'^[bcdfghjklmnpqrstvwxyz]+$') 
>>> [word for word in words if pattern.match(word)] 
['xkcd']