Reputation: 487
I have two lists of strings in Python. One of them is a list of desired strings, the other is a larger list of different strings. For example:
desired = ["cat52", "dog64"]
buf = ["horse101", "elephant5", "dog64", "mouse90", "cat52"]
I need a True/False for whether the second list contains all the strings in the first list. So far I did this with:
if all(element in buf for element in desired)
However, now I need the list of desired strings to have some regex properties. For example:
desired = ["cat52", "dog[0-9]+"]
I've looked into the re
and regex
python libraries but I can't figure out a statement that gives me what I want. Any help would be appreciated.
Upvotes: 1
Views: 1303
Reputation: 147166
You need to test whether any
of the strings in buf
match each regex in desired
, and then return True
if all
of them do:
import re
buf = ["horse101", "elephant5", "dog64", "mouse90", "cat52"]
desired = ["cat52", "dog[0-9]+"]
print(all(any(re.match(d + '$', b) for b in buf) for d in desired))
Output:
True
Note that we add $
to the regex so that (for example) dog[0-9]+
will not match dog4a
(adding ^
to the beginning is not necessary as re.match
anchors matches to the start of the string).
Upvotes: 2