1

I have an existing python script that, among other things checks a file against a dictionary of regular expressions. If the file contains one of the regular expressions, I note that a dictionary hit has been made, print the line that contains the file and move on. Pretty simple.

However I now want to establihs a different callback function for each RE the file has a hit against. I'm puzzled as to how this can be accomplished in python outside of a long if/elseif block. Is this a case where this should be done in PERL instead? (This means I have to re-write quite a bit of code, hence the reason for not doing so in the first place).

I've checked these out (even the links in the posts) for possible work-arounds but have yet to see anything that might work:

Replacements for switch statement in Python?

https://stackoverflow.com/questions/374239/why-doesnt-python-have-a-switch-statement

Community
  • 1
  • 1
WildBill
  • 9,143
  • 15
  • 63
  • 87

1 Answers1

4

You could do something like this :

def callback1(line, regex_match):
   #do what you want

def callback2(line, regex_match):
   #do what you want... else


regex_dict = {
   "first_regex" : callback1,
   "second_regex" : callback2,
}

file_to_check = open("the_file")
for line in file_to_check:
    for regex, callback in regex_dict.iteritems():
        result = re.match(regex, line)
        if result:
           callback(line, result)
           break

Then, on each regex match you will call the callback associated with the line and the regex result.

Cédric Julien
  • 78,516
  • 15
  • 127
  • 132