I need to try a string against multiple (exclusive - meaning a string that matches one of them can't match any of the other) regexes, and execute a different piece of code depending on which one it matches. What I have currently is:
m = firstre.match(str)
if m:
# Do something
m = secondre.match(str)
if m:
# Do something else
m = thirdre.match(str)
if m:
# Do something different from both
Apart from the ugliness, this code matches against all regexes even after it has matched one of them (say firstre), which is inefficient. I tried to use:
elif m = secondre.match(str)
but learnt that assignment is not allowed in if statements.
Is there an elegant way to achieve what I want?
Regex search groups or multiple patterns On a successful search, we can use match. group(1) to get the match value of a first group and match. group(2) to get the match value of a second group. Now let's see how to use these two patterns to search any six-letter word and two consecutive digits inside the target string.
Regular Expressions (“regex” or “regexp”), are used to match strings of text such as particular characters, words, or patterns of characters. In python we have a built-in package called "re" to work with regular expressions.
A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.
def doit( s ):
# with some side-effect on a
a = []
def f1( s, m ):
a.append( 1 )
print 'f1', a, s, m
def f2( s, m ):
a.append( 2 )
print 'f2', a, s, m
def f3( s, m ):
a.append( 3 )
print 'f3', a, s, m
re1 = re.compile( 'one' )
re2 = re.compile( 'two' )
re3 = re.compile( 'three' )
func_re_list = (
( f1, re1 ),
( f2, re2 ),
( f3, re3 ),
)
for myfunc, myre in func_re_list:
m = myre.match( s )
if m:
myfunc( s, m )
break
doit( 'one' )
doit( 'two' )
doit( 'three' )
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