If you are just trying to match literal strings, this is probably simpler:
strings = 'foo','bar','baz','qux' regex = re.compile('|'.join(re.escape(x) for x in strings))
and then you can immediately check all of this:
match = regex.match(line)
Of course, you can get a string that matches the resulting MatchObject:
if match: matching_string = match.group(0)
In action:
import re strings = 'foo','bar','baz','qux' regex = re.compile('|'.join(re.escape(x) for x in strings)) lines = 'foo is a word I know', 'baz is a word I know', 'buz is unfamiliar to me' for line in lines: match = regex.match(line) if match: print match.group(0)
It seems that you are really looking for a string to search for your regular expression. In this case, you need to use re.search (or some option) and not re.match , no matter what you do. As long as none of your regular expressions overlap, you can use my solution above with re.findall :
matches = regex.findall(line) for word in matches: print ("found {word} in line".format(word=word))
source share