narainhere has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, I would like to do a regex on a string, to see if it matches any of the strings in a array. Right now I am doing this by
@arr=('cool','guy','here'); $str1="I am cool"; foreach my $tmp(@arr){ if($str1=~m/$tmp/){ print "Matched"; last; } }
This works and matches fine,but I wanted to improve on this as
@arr=(cool,guy,here); $str1="I am cool"; if($str1 =~ m/@arr/){ print "Matched"; }
Though no error is shown this one fails to match.Any explanations???

The world is so big for any individual to conquer

Replies are listed 'Best First'.
Re: Mathching an array in regex
by ikegami (Patriarch) on Oct 12, 2007 at 11:46 UTC

    When you put an array into a string or regex literal, it gets expanded to join($", @arr) (/cool guy here/ in this case.)

    • One rather good solution is:

      my @arr = qw( cool guy here ); my $str = "I am cool"; my $re = "(?:" . (join '|', map quotemeta, @arr) . ")"; if ($str =~ $re) { # if ($str =~ /^$re$/) { print "Matched\n"; # print "Equals\n"; } # }

      I used quotemeta because I presumed your array holds strings and not regexs.

    • If your array contains many elements and you want a bit more speed, you could use Regexp::List.

      use Regexp::List qw( ); my @arr = qw( cool guy here ); my $str = "I am cool"; my $re = Regexp::List->new(@arr)->list2re(); if ($str =~ $re) { # if ($str =~ /^$re$/) { print "Matched\n"; # print "Equals\n"; } # }

      Regexp::List accepts a list of text. If you had a list of regexps, you'd use Regexp::Assemble instead.

    • Of course, you could avoid regexs entirely.

      my @arr = qw( cool guy here ); my $str = "I am cool"; if (grep {index($str,$_)!=-1} @arr) { # if (grep {$str eq $_} @arr) { print "Matched\n"; # print "Equals\n"; } # }

    Update: Added johngg's version for symetry. Originally, I only had the "Equals" version for grep.

      I'm not sure that last code snippet is going to work. Perhaps using index inside the grep would?

      if ( grep { index($str, $_) != -1 } @arr ) { ...

      Cheers,

      JohnGG

Re: Mathching an array in regex
by Krambambuli (Curate) on Oct 12, 2007 at 12:00 UTC
    That won't work like that. To see what's happening, try

    perl -MO=Deparse test.pl

    on the code put in test.pl. For
    #!/usr/bin/perl use strict; use warnings; my @arr=('cool','guy','here'); my $str1="I am cool"; if($str1 =~ m/@arr/){ print "Matched"; }
    this will show you
    $ perl -MO=Deparse test.pl use warnings; use strict 'refs'; my(@arr) = ('cool', 'guy', 'here'); my $str1 = 'I am cool'; if ($str1 =~ /@arr/) { print 'Matched'; } test.pl syntax OK
    Note that /@arr/ is taken literally - it so has to be, only scalars are interpolated inside regexes, not arrays. You might try something like
    #!/usr/bin/perl use strict; use warnings; my @arr=('cool','guy','here'); my $joined_rx = join( '|', map { quotemeta($_) } @arr ); my $str1="I am cool"; if ($str1 =~ m/$joined_rx/) { print "Matched"; }
    but I'd prefere the solution with a loop/map based on the given array.

    Hth.

    Update: ikegami is right, of course. @ _is_ expanded in regexes too - but the extra spaces it introduces makes the resulting rx something that's far away from what was intended. My bad, sorry.
      Thanks for introducing me to perl -MO utility, can you direct me to the documentation on that, I don't find it in perldoc:perl -MO=Deparse test.pl.I disagree with you on the point that @arr is not expanded, the following code produces Matched as o/p (Note the $str1 value and array)
      #!/usr/bin/perl use strict; use warnings; my @arr=('cool','guy','here'); my $str1="cool guy here"; if($str1 =~ m/@arr/){ print "Matched"; }

      The world is so big for any individual to conquer

        Look for B::Deparse for the docs. The module is unvaluable sometimes

        To the @ expansion in regexes: you're right, of course. I think I just never have tried it, and so I had an 'explanation' at hand.
        Sorry.
Re: Mathching an array in regex
by jeanluca (Deacon) on Oct 12, 2007 at 12:17 UTC
    you are almost there, do it like this
    #!/usr/bin/perl -l use strict ; use warnings ; my @arr= qw(cool guy here); my $str1="I am cool"; local $" = "|" ; if($str1 =~ m/@arr/){ print "Matched"; }
    Cheers
    LuCa
Re: Mathching an array in regex
by mwah (Hermit) on Oct 12, 2007 at 12:12 UTC
    There have been concise explanations for the
    behavior you found.

    I'd use a core module (List::Util) for that:
    use List::Util qw(first); my @arr=('cool','guy','here'); my $str1="I am cool"; my $hit = first{ $str1 =~ /\Q$_/ } @arr; print "Matched $hit";
    Regards

    mwa
Re: Mathching an array in regex
by mwah (Hermit) on Oct 12, 2007 at 16:09 UTC
    narainhereHi monks, I would like to do a regex on a string, to see if it matches any of the strings in a array

    After reading the solutions here, I was tempted to
    post a second contribution (which I do now).

    The topic is interesting because so many
    ways exist to solve it. My question was then:
    what are they worth in real code. Stressing the
    point of the OP: "to see if it matches any of the strings in a array",
    it's clear that the grep/map-solutions do too much here.
    But what about the regex-only solution?

    Here's my first attempt to get behind that:
    use strict; use warnings; use List::Util qw'first reduce'; use Benchmark qw'cmpthese timethese'; my @arr = qw' cool guy here ' x 1; my $str = '100 WORDS ' x 50 . 'I am cool'; my @invocation=(0)x5; my $results = timethese(0, { 'word_altn' => sub { local $" = '|'; if( $str =~ /@arr/ ) { ++$invocation[0]; # print "Matched\n" } }, 'block_grep' => sub { if( grep { index($str, $_) !=-1 } @arr) { ++$invocation[1]; # print "Matched\n" } }, 'expr_grep' => sub { if( grep index($str, $_) !=-1, @arr) { ++$invocation[2]; # print "Matched\n" } }, 'list_util_index' => sub { if( first { index($str, $_) != -1 }, @arr ) { ++$invocation[3]; #print "Matched\n" } }, 'list_util_regex' => sub { if( first { $str =~ /$_/ }, @arr ) { ++$invocation[4]; #print "Matched\n" } } }, 'none' ); print "@invocation\n"; die unless 5 == grep $_>0, @invocation; cmpthese $results;
    On my Linux box (5.8.8), this will produce:
    42598 1157019 1349175 990717 1135313 Rate word_altn list_util_index list_util_regex blo +ck_grep expr_grep word_altn 10213/s -- -96% -97% + -97% -97% list_util_index 274237/s 2585% -- -8% + -16% -20% list_util_regex 299705/s 2835% 9% -- + -8% -13% block_grep 325087/s 3083% 19% 8% + -- -5% expr_grep 342754/s 3256% 25% 14% + 5% --
    On larger strings *or* larger comparison word arrays,
    the List::Util based solutions will tend to win
    by a margin.

    Regards

    mwa
      The most idiomatic and most easily-understandable solution for "does a string contain any of these items" is:

          if ( grep { $str =~ /$_/ } @arr ) { ... }

      I ran the test again, with this new strategy added and a few other changes to the code:

      • $str and @arr are each longer
      • the matchword occurs in the middle of $str and @arr. This should make the solutions using first() more effective.
      • some of the test names are changed to better describe what they do

      Also, there is a small but important bug in your code:

        first BLOCK, ARRAY

      should be:

        first BLOCK ARRAY

      The former will only run the BLOCK once, regardless of outcome, and throw away the result. (Oh Perl syntax, why must you be so baroque?)

      So how does the new method fare in this adjusted test?

      word_altn 506/s grep_block_index 2356/s was: block_grep grep_expr_index 2373/s was: expr_grep grep_block_regex 3957/s <-- new method here first_index 4179/s was: list_util_index first_regex 6871/s was: list_util_regex
      The pleasant surprise is that a plain grep-regex solution turns out to be faster than replacing the regex with an index() call. Replacing grep() with first() gives a further speedup of about 75%, but as we've just seen you lose some maintainability, and that can be important.

      New code:

Re: Mathching an array in regex
by lali (Initiate) on Oct 12, 2007 at 18:56 UTC
    Hi, I tried it like this, #!/usr/bin/perl use strict; my @array = ('cool','guy','here'); print "Enter any word among cool/guy/here: "; my $input = <STDIN>; chomp $input; my $match=0; foreach (@array){ if ($_ =~ /$input/i){ $match=1; } } if ($match == 1){ print "String matched\n"; }else{ print "No match.\n"; }
Re: Mathching an array in regex
by ryanc (Monk) on Oct 15, 2007 at 23:58 UTC
    what about?
    use strict; use warnings; my @arr = ('cool', 'guy', 'here'); my $str = "I am cool"; print "Matched.\n" if grep { $str =~ /$_/ } @arr;