在字符串中搜索匹配词的最佳方法是什么?
现在我做了类似下面的事情:
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']
关于python正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3962241/