Match A List Of Words In A Line Using Regex In Python
I am looking for an expression to match strings against a list of words like ['xxx', 'yyy', 'zzz']. The strings need to contain all three words but they do not need to be in the sa
Solution 1:
Simple string operation:
mywords = ("xxx", "yyy", "zzz")
all(x in mystring for x in mywords)
If word boundaries are relevant (i. e. you want to match zzz
but not Ozzzy
):
import re
all(re.search(r"\b" + re.escape(word) + r"\b", mystring) for word in mywords)
Solution 2:
I'd use all
and re.search
for finding matches.
>>> words = ('xxx', 'yyy' ,'zzz')
>>> text = "sdfjhgdsf zzz sdfkjsldjfds yyy dfgdfgfd xxx"
>>> all([re.search(w, text) for w in words])
True
Post a Comment for "Match A List Of Words In A Line Using Regex In Python"