如何使用python中的列表进行re.compile() [英] how to do re.compile() with a list in python
问题描述
我有一个字符串列表,我想在其中过滤包含关键字的字符串.
I have a list of strings in which I want to filter for strings that contains keywords.
我想做类似的事情:
fruit = re.compile('apple', 'banana', 'peach', 'plum', 'pinepple', 'kiwi']
所以我可以使用 re.search(fruit, list_of_strings) 只获取包含水果的字符串,但我不确定如何使用带有 re.compile 的列表.有什么建议么?(我不打算使用 re.compile,但我认为正则表达式是一个很好的方法.)
so I can then use re.search(fruit, list_of_strings) to get only the strings containing fruits, but I'm not sure how to use a list with re.compile. Any suggestions? (I'm not set on using re.compile, but I think regular expressions would be a good way to do this.)
推荐答案
你需要把你的水果列表变成字符串 apple|banana|peach|plum|pineapple|kiwi
以便它是一个有效的正则表达式,以下内容应该为您执行此操作:
You need to turn your fruit list into the string apple|banana|peach|plum|pineapple|kiwi
so that it is a valid regex, the following should do this for you:
fruit_list = ['apple', 'banana', 'peach', 'plum', 'pineapple', 'kiwi']
fruit = re.compile('|'.join(fruit_list))
edit:正如 ridgerunner 在评论中指出的那样,您可能希望向正则表达式添加单词边界,否则正则表达式将匹配像 plump
这样的单词,因为它们有一个水果作为子串.
edit: As ridgerunner pointed out in comments, you will probably want to add word boundaries to the regex, otherwise the regex will match on words like plump
since they have a fruit as a substring.
fruit = re.compile(r'\b(?:%s)\b' % '|'.join(fruit_list))
这篇关于如何使用python中的列表进行re.compile()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!