[Mpls-pm] Interesting RegEx Problem

Ian Malpass ian at indecorous.com
Mon Sep 19 08:55:45 PDT 2005


On Mon, 19 Sep 2005, Robert Fischer wrote:

> I've got a problem that just came up at work.  Any help?
>
> Given an arbitrary string and a collection of regular expressions, and
> assuming that one and only one of the regular expressions match the
> string, what is the best way to find the matching regular expression?

Are you looking for something more efficient than trying each one until 
you find one that matches?

If not, this would work, I think:

     use strict;
     use warnings;

     my $string = "A fool and his money are soon parted";

     my %patterns = (
         foo => qr/foo/,
         bar => qr/bar/,
         baz => qr/baz/
     );

     while ( my ( $name, $pattern ) = each %patterns ) {
         if ( $string =~ $pattern ) {
             print "Matched $name\n";
             last;
         }
     }

Tries them in hash-random order.

Ian

P.S. Gypsy's if/elsif solution is also fine, but requires a bit more 
cut-and-paste when adding or removing patterns later. Depends on the 
number of patterns you have, and how often they change, I suppose. Also a 
judgement call on which is easier for other coders to understand. I 
personally prefer mine (but then I suppose I would) since there's no 
duplicated code.

-
---------------------------------------------------------------------------

The soul would have no rainbows if the eyes held no tears.

Ian Malpass
<ian at indecorous.com>


More information about the Mpls-pm mailing list