I have a list of patterns like
list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to']
what I want to do is to produce a union of all of them yielding a regular expression that matches every element in list_patterns [but presumably does not match any re not in list_patterns — msw]
re.compile(list_patterns)
Is this possible?
There are a couple of ways of doing this. The simplest is:
Output:
which is fine as long as concatenating your search patterns doesn’t break the regex (eg if one of them contains a regex special character like an opening parenthesis). You can handle that this way:
Output is the same. But what this does is pass each pattern through
re.escape()to escape any regex special characters.Now which one you use depends on your list of patterns. Are they regular expressions and can thus be assumed to be valid? If so, the first would probably be appropriate. If they are strings, use the second method.
For the first, it gets more complicated however because by concatenating several regular expressions you may change the grouping and have other unintended side effects.