Regex in if statement.

Rhodri James rhodri at wildebst.demon.co.uk
Sun Mar 20 21:29:44 EDT 2011


On Mon, 21 Mar 2011 00:46:22 -0000, Ken D'Ambrosio <ken at jots.org> 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?

The basic routine is to do the match and test the returned object:

match_obj = re.match(pattern, string)
if match_obj is not None:
   do_something(match_obj)

If you don't need the match object (you aren't doing group capture,
say), obviously you can fold the first two of those lines together.

This can be a bit of a pain if you have a chain of tests to do
because of having to stop to save the match object.  To get around
that, wrap the match in something that stashes the match object.
Here's a primitive class-based version:

import re

class Match(object):
   def __init__(self):
     self.match_obj = None

   def match(self, *args, **kwds):
     self.match_obj = re.match(*args, **kwds)
     return self.match_obj is not None

match = Match()
if match.match(pattern1, string1):
   do_something(match.match_obj)
elif match.match(pattern2, string2):
   do_something_else(match.match_obj)

Knowing more about what it is you want to do, you should be able
to do better than that.  As other people have said though,
regular expressions are often overkill, and it's worth thinking
about whether they really are the right answer to your problem.
Coming from Perl, it's easy to get into the mindset of applying
regexes to everything regardless of how appropriate they are.  I
certainly did!

-- 
Rhodri James *-* Wildebeest Herder to the Masses



More information about the Python-list mailing list