Skip to content Skip to sidebar Skip to footer

Re-use Of A Regular Expression Capture Group In Python

The following python code does work but the regular expression 'search' is evaluated twice: # my_string varies, it gets the following strings = ['%10s', 'comma%11d', 'comma%-6

Solution 1:

It can easily be done via assigning the re.search result to a variable and then checking if the variable is not None:

m = re_compiled_pat_int.search(my_string)
if m isnotNone:   # or 'if m:' will do, too# Do something

In Python 3.8, there is an option to get the match object in the if condition using a walrus operator :=:

if (match := re_compiled_pat_int.search(my_string)) isnotNone:
    # Do something withmatch

See more info about the walrus operator introduction:

Python 3.8 has a new walrus operator := that assigns values to variables as part of a larger expression. It is useful when matching regular expressions where match objects are needed twice. It can also be used with while-loops that compute a value to test loop termination and then need that same value again in the body of the loop. It can also be used in list comprehensions where a value computed in a filtering condition is also needed in the expression body.

The walrus operator was proposed in PEP 572 (Assignment Expressions) by Chris Angelico, Tim Peters, and Guido van Rossum last year. Since then it has been heavily discussed in the Python community with many questioning whether it is a needed improvement. Others are excited as the operator does make the code more readable.

Post a Comment for "Re-use Of A Regular Expression Capture Group In Python"