Starting with this:
stringloop = ['lorem 123', 'testfoo', 'dolor 456']
key = ['lorem', 'ipsum', 'dolor']
First, you need to match any one key. Use the |
joining operator. x|y|z
looks for x
or y
or z
. Create the object outside the loop:
matcher = re.compile('|'.join(map(re.escape, key)), re.I) # escaping possible metacharacters
Here, I use re.escape
to escape any possible regex metacharacters. May not work if your existing pattern has any meta characters. Now loop through stringloop
, calling matcher.match
on each item. Don't use filter
, call it directly:
for item in stringloop:
if matcher.match(item):
print(item)
This gives:
lorem 123
dolor 456
For complicated patterns with their own meta characters, you should probably compile each pattern separately in a pattern list:
matchers = [re.compile(pat, re.I) for pat in key]
You'll then modify your loop slightly:
for item in stringloop:
for m in matchers:
if m.match(item):
print(item)
break
This also works, giving:
lorem 123
dolor 456
But it is slower, because of the nested loop.
As a closing comment, if your keys are simple strings, I would just go with str.startswith
, because that also does the same thing, checking if a string begins with a certain sub string:
for item in stringloop:
if item.lower().startswith(tuple(key)):
print(item)
Magically, this also gives:
lorem 123
dolor 456