Skip to content Skip to sidebar Skip to footer

Python Regex For Conditional (|) Matching

Looking for a python regex pattern. Seems like it has to exist, but it has me stumped. If I need to find an address, and the strings I am searching can be of the form address_is_a

Solution 1:

You could do it with lookarounds, provided that the length of the lookbehind ("address_is_after_") is constant:

>>>m = re.search(r"(?<=address_is_after_)\d+|\d+(?=_address_is_before)",text)>>>m.group(0)
'123'

Solution 2:

You don't need to test which group has the match. An unmatched group returns None, which is treated as false by or:

>>>for text in ["address_is_after_123", "123_address_is_before"]:...            m = re.match("(?:address_is_after_(\d+)|(\d+)_address_is_before)",text)...print(m.group(1) or m.group(2))...
123
123

Post a Comment for "Python Regex For Conditional (|) Matching"