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

Hi all, sorry if this is a naive question but I've searched around the web and haven't found a good answer, including https://perldoc.perl.org/perlre#Metacharacters.

How do I match a regex that contains metacharacters that are used in matching, such as asterisks, parens, etc.? Without escaping each?

I have two variables set, both containing asterisks, and a regex comparison:

#! /usr/bin/perl my $v1 = "*hello"; my $v2 = "*hello"; if ($v1 =~ /$v2/){ print "match\n"; }

This obviously results in a Quantifier follows nothing in regex error. I can escape out the asterisk and it works fine:

$v2 =~ s/\*/\\\*/g;

But is there a more elegant way to do that, one that might also pick up some of the others?

thanks

Replies are listed 'Best First'.
Re: regex matching on metacharacters
by LanX (Saint) on Jul 21, 2022 at 00:06 UTC
    > But is there a more elegant way to do that, one that might also pick up some of the others?

    yes, see quotemeta resp. \Q and \E °

    demo
    >perl $v1 = "*hello"; $v2 = "*hello"; print quotemeta($v2),"\n"; print "match" if $v1 =~ /\Q$v2/; __END__ \*hello match >

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

    °) also perlre#Quoting-metacharacters

      thank you!

Re: regex matching on metacharacters
by hippo (Archbishop) on Jul 21, 2022 at 09:15 UTC

    Do you really want a regex match or are you actually trying to perform a substring match? If the latter, then consider index instead.

    #!/usr/bin/env perl use strict; use warnings; my $str = 'You say *hello, but you mean *goodbye.'; my $substr = '*hello'; print "match\n" if index ($str, $substr) > -1;

    🦛