checking a string against multiple patterns

Tim Chase python.list at tim.thechases.com
Tue Dec 18 08:25:50 EST 2007


> Define a small function with each test+action, and iterate over them
> until a match is found:
> 
> def check1(input):
>   match = re.search(pattern1, input)
>   if match:
>     return input[:match.end(1)]
> 
> def check2(input):
>   match = re.search(pattern2, input)
>   if match:
>     return ...
> 
> for check in check1, check2, check3:
>   result = check(input)
>   if result is not None:
>     break
> else:
>   # no match found

Or, one could even create a mapping of regexps->functions:

 def function1(match):
   do_something_with(match)

 def function2(match):
   do_something_with(match)

 def default_function(input):
   do_something_with(input)

 function_mapping = (
   (re.compile(pattern1), function1),
   (re.compile(pattern2), function2),
   (re.compile(pattern3), function1),
   )

 def match_and_do(input, mapping):
   for regex, func in mapping:
     m = regex.match(input)
     if m: return func(m)
   return default_function(input)

 result = match_and_do("Hello world", function_mapping)

In addition to having a clean separation between patterns and
functions, and the mapping between them, this also allows wiring
multiple patterns to the same function (e.g. pattern3->function1)
and also allows specification of the mapping evaluation order.

-tkc






More information about the Python-list mailing list