Skip to content Skip to sidebar Skip to footer

Pythonic Way To Concatenate Regex Objects

I have python regex objects - say, re_first and re_second - I would like to concatenate. import re FLAGS_TO_USE = re.VERBOSE | re.IGNORECASE re_first = re.compile( r'''abc #Some co

Solution 1:

I don't think you will find a solution that doesn't involve creating a list with the regex objects first. I would do it this way:

# create patterns here...re_first = re.compile(...)
re_second = re.compile(...)
re_third = re.compile(...)

# create a list with themregexes = [re_first, re_second, re_third]

# create the combined onepattern_combined = '|'.join(x.pattern for x in regexes)

Of course, you can also do the opposite: Combine the patterns and then compile, like this:

pattern1 = r'pattern-1'
pattern2 = r'pattern-2'
pattern3 = r'pattern-3'

patterns = [pattern1, pattern2, pattern3]

compiled_combined = re.compile('|'.join(x for x in patterns), FLAGS_TO_USE)

Solution 2:

Solution 3:

One can also directly concatenate r strings, for example:

prep_re = r"\b" + r"\b|\b".join(prepositions) + r"\b"
re.findall(prep_re, paragraph, re.IGNORECASE)

Post a Comment for "Pythonic Way To Concatenate Regex Objects"