Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I search through regex matches in Python?

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?

like image 384
Sundar R Avatar asked Jan 08 '10 14:01

Sundar R


People also ask

How do I search for multiple patterns in Python?

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.

Which Python library is used for regex search?

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.

How do regex searches work?

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.


1 Answers

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' ) 
like image 106
Philippe F Avatar answered Oct 02 '22 00:10

Philippe F