in reply to creating a regular expression's alternation dynamically?

#!/usr/bin/perl use strict; # create alternation my @list; while (<DATA>) { chomp; push @list, $_; } my $regex = '^(' . join('|', @list) . ')$'; my $s = 'huey'; print "regex = $regex\n"; print "match:\t$1\n" if $s =~ m/$regex/; __DATA__ huey dewey louie
Running the program...
C:\Temp\test>perl test.pl regex = ^(huey|dewey|louie)$ match: huey

Replies are listed 'Best First'.
Re^2: creating a regular expression's alternation dynamically?
by integral (Hermit) on Aug 06, 2004 at 14:39 UTC

    In the join, you might want to map quotemeta over @list so that any meta-chars (particulary |) get escaped.

    Also you have to be careful that none of the strings are prefixes of another string, otherwise you'll find that ordering is significant in an alternation.

    --
    integral, resident of freenode's #perl
    
      yep, good point, thanks!
      use strict; use warnings; # create alternation my @list; while (<DATA>) { chomp; push @list, $_; } my $regex = '^(' . join('|', map {quotemeta} @list) . ')$'; my $s = 'huey'; print "regex = $regex\n"; print "match:\t$1\n" if $s =~ m/$regex/; __DATA__ huey de|wey louie
      output is...
      # perl test.pl regex = ^(huey|de\|wey|louie)$ match: huey