Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

regex - 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.

I want to do something like:

fruit = re.compile('apple', 'banana', 'peach', 'plum', 'pinepple', 'kiwi']

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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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: 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'(?:%s)' % '|'.join(fruit_list))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...