tags:

views:

171

answers:

1

hi,

i have a list of regex patterns (stored in a list type) that I would like to apply to a string.

Does anyone know a good way to:

  1. Apply every regex pattern in the list to the string and
  2. Call a different function that is associated with that pattern in the list if it matches.

I would like to do this in python if possible

thanks in advance.

+5  A: 
import re

def func1(s):
    print s, "is a nice string"

def func2(s):
    print s, "is a bad string"

funcs = {
    r".*pat1.*": func1,
    r".*pat2.*": func2
}
s = "Some string with both pat1 and pat2"

for pat in funcs:
    if re.search(pat, s):
        funcs[pat](s)

The above code will call both functions for the string s because both patterns are matched.

Eli Courtwright
You don't even need the list (pats), just use 'for pat in funcs'.
too much php
+1: Nice, readable. --- But skip the pats list, just iterate "for pat, func in funcs.items()".
Deestan
Minor nit: A regular expression cannot start with a star.
Greg Hewgill
I agree that the list is unnecessary; I only included it because the question asked for it. However, I've gone ahead and removed it since I agree that it would make the code much cleaner and more Pythonic.
Eli Courtwright
Greg: my bad; I meant to say .* instead of just * and I've edited my code to fix this.
Eli Courtwright
@Eli: If you are using `re.search` then '.*'s are unnecessary in this case.
J.F. Sebastian
+1 after improvements :)
Greg Hewgill
cheers, just what i asked for. good answer
DEzra
@J.F.Sebastian: I agree that re.search would be better for the two patterns which I used, but the question asked for using matches, which is why I did things that way.
Eli Courtwright
Um. Why a dictionary, and not a list of tuples?
ΤΖΩΤΖΙΟΥ
I was guessing that somewhere else in a program using this code, someone might want to do a simple function lookup with a regex. Also I like the way that dictionary literals look more than I like the look of lists of tuples.
Eli Courtwright