[Mpls-pm] Interesting RegEx Problem

Gypsy Rogers gypsy at freeq.com
Mon Sep 19 09:12:01 PDT 2005



Like I said, one of my biggest motivations recently has become to make sure
I don't have to spend time explaining my code to someone else when I hand it
off to them to maintain. 


That being said, yeah, if you have more then 3
expressions to check the loop is probably the way to go. I just threw out
the first thing to pop to my mind. :)


On Mon, 19 Sep 2005 16:55:45 +0100 (BST), Ian Malpass <ian at indecorous.com>
wrote :

> 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>
> _______________________________________________
> Mpls-pm mailing list
> Mpls-pm at pm.org
> http://mail.pm.org/mailman/listinfo/mpls-pm
> 
> 
> 


More information about the Mpls-pm mailing list