I've got a list of exact patterns that I want to search in a given string. Currently I've got a real bad solution for such a problem.
pat1 = re.compile('foo.tralingString')
mat1 = pat1.match(mystring)
pat2 = re.compile('bar.trailingString')
mat2 = pat2.match(mystring)
if mat1 or mat2:
# Do whatever
pat = re.compile('[foo|bar].tralingString')
match = pat.match(mystring) # Doesn't work
The only condition is that I've got a list of strings which are to be matched exactly. Whats the best possible solution in Python.
EDIT: The search patterns have some trailing patterns common.
Exact match (equality comparison): == , != As with numbers, the == operator determines if two strings are equal. If they are equal, True is returned; if they are not, False is returned. It is case-sensitive, and the same applies to comparisons by other operators and methods.
Use the all() function to check if multiple strings exist in another string, e.g. if all(substring in my_str for substring in list_of_strings): . The all() function will return True if all of the substrings exist in the string and False otherwise.
re.MatchObject.group() method returns the complete matched subgroup by default or a tuple of matched subgroups depending on the number of arguments.
You could do a trivial regex that combines those two:
pat = re.compile('foo|bar')
if pat.match(mystring):
# Do whatever
You could then expand the regex to do whatever you need to, using the |
separator (which means or in regex syntax)
Edit: Based upon your recent edit, this should do it for you:
pat = re.compile('(foo|bar)\\.trailingString');
if pat.match(mystring):
# Do Whatever
The []
is a character class. So your [foo|bar]
would match a string with one of the included characters (since there's no * or + or ? after the class). ()
is the enclosure for a sub-pattern.
You're right in using |
but you're using a character class []
instead of a subpattern ()
. Try this regex:
r = re.compile('(?:foo|bar)\.trailingString')
if r.match(mystring):
# Do stuff
Old answer
If you want to do exact substring matches you shouldn't use regex.
Try using in
instead:
words = ['foo', 'bar']
# mystring contains at least one of the words
if any(i in mystring for i in words):
# Do stuff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With