Regex in if statement.

Thomas L. Shinnick tshinnic at io.com
Sun Mar 20 21:36:57 EDT 2011


At 07:46 PM 3/20/2011, Ken D'Ambrosio wrote:
>Hey, all -- I know how to match and return stuff from a regex, but I'd
>like to do an if, something like (from Perl, sorry):
>
>if (/MatchTextHere/){DoSomething();}
>
>How do I accomplish this in Python?

You say you've done matching and accessing stuff from the regex match 
result, something like this longhand:
         mo = text_password_guard_re.match( text )
         if mo:
             text = mo.group(1) + " ******"
The above captured the match object result value and then checked 
that result.  If no match then the result value would be None and the 
if would not execute.

The above used a pre-compiled regex and called .match() on that.  You 
can instead use a pattern string directly.
         mo = re.match(r"foo(\d+)", text)
         if mo:
             text = mo.group(1) + " ******"

And if you don't need any captures (as you say) then you can just use 
the call in the if directly:
         if re.match(r"foo\d+", text):
             print("foo multiplied!")

And the above examples used .match(), to match starting from the 
beginning of the text string, but you can also use .search()
         if re.search(r"foo", text):
             print("foo found somewhere in text!")

To my mind Python wants to require all usages/contexts be explicit, 
requiring elaborations on your intent, whereas Perl was rather more 
happy to try to understand your intentions with what little you gave 
it.  Enter much disputation here.

Anyway, read all you can, especially any Python code you can lay your 
hands on, get the mindset from that, and just code.

>Thanks!
>
>-Ken




More information about the Python-list mailing list