Skip to main content
 首页 » 编程设计

python正则表达式问题

2025年05月04日25sxdcgaq8080

在字符串中搜索匹配词的最佳方法是什么?

现在我做了类似下面的事情:

if re.search('([h][e][l][l][o])',file_name_tmp, re.IGNORECASE): 

这行得通,但速度很慢,因为我可能有大约 100 个不同的正则表达式语句来搜索完整的单词,所以我想使用 | 组合几个。分隔符或其他东西。

请您参考如下方法:

>>> words = ('hello', 'good\-bye', 'red', 'blue') 
>>> pattern = re.compile('(' + '|'.join(words) + ')', re.IGNORECASE) 
>>> sentence = 'SAY HeLLo TO reD, good-bye to Blue.' 
>>> print pattern.findall(sentence) 
['HeLLo', 'reD', 'good-bye', 'Blue']