Best way to extract from regex in if statement

Tim Chase python.list at tim.thechases.com
Fri Apr 3 22:11:04 EDT 2009


bwgoudey wrote:
> I have a lot of if/elif cases based on regular expressions that I'm using to
> filter stdin and using print to stdout. Often I want to print something
> matched within the regular expression and the moment I've got a lot of cases
> like:
> 
> ...
> elif re.match("^DATASET:\s*(.+) ", line):
>         m=re.match("^DATASET:\s*(.+) ", line)
>         print m.group(1))
> 
> 
> which is ugly because of the duplication but I can't think of a nicer of way
> of doing this that will allow for a lot of these sorts of cases. Any
> suggestions?

I've done this in the past with re-to-function pairings:

   def action1(matchobj):
     print matchobj.group(1)
   def action2(matchobj):
     print matchobj.group(3)
   # ... other actions to perform

   searches = [
     (re.compile(PATTERN1), action1),
     (re.compile(PATTERN2), action2),
     # other pattern-to-action pairs
     ]

   # ...
   line = ...
   for regex, action in searches:
     m = regex.match(line)
     if m:
       action(m)
       break
   else:
     no_match(line)

(note that that's a for/else loop, not an if/else pair)

-tkc








More information about the Python-list mailing list