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

Is it possible to use a string as the basis for a regex?

i.e. $str =~ |$pattern_str|

I tried some escaping and looked all over but couldn't find an answer to this.
  • Comment on Regexes that use a string as basis for matching

Replies are listed 'Best First'.
Re: Regexes that use a string as basis for matching
by holli (Abbot) on Jun 14, 2008 at 21:59 UTC
    you mean like
    $s = "match"; $re = qr/$s/; print "yup" if $something =~ $re;
    or even simpler (but slower)
    $s = "match"; print "yup" if $something =~ /$s/;


    holli, /regexed monk/
      The second snippet shouldn't be any slower. In both snippets, the regexp is compiled once.

      However,

      my @regexps = ( 'pattern1', 'pattern2', ); for my $s (@strings) { for $re (@regexps) { something($s =~ /$re/); } }

      is slower than

      my @regexps = ( qr/pattern1/, qr/pattern2/, ); for my $s (@strings) { for $re (@regexps) { something($s =~ /$re/); } }

      since the former compiles each regexp for each string, while the latter compiles each regexp once.

      or even simpler (but slower)

      Why is it slower?

      oooh thanks, that worked perfectly
Re: Regexes that use a string as basis for matching
by ikegami (Patriarch) on Jun 15, 2008 at 00:16 UTC

    If $pattern_str is plain text and not a regular expression, you'll need to convert/escape it before you can use it as a regular expression.

    $str =~ /\Q$text\E/
    or
    my $re = quotemeta($text); $str =~ /$re/
    or
    index($str, $text) >= 0

    References:
    perlre (for regular expressions in general and \Q..\E specifically)
    quotemeta
    index

Re: Regexes that use a string as basis for matching
by FunkyMonk (Bishop) on Jun 15, 2008 at 00:05 UTC
    Matching against a variable is mentioned in perlre and is the fourth example in perlre. Perhaps the official documentation is where you should have looked first

    Unless I state otherwise, all my code runs with strict and warnings