Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

regex matching on metacharacters

by slugger415 (Monk)
on Jul 20, 2022 at 23:56 UTC ( [id://11145616]=perlquestion: print w/replies, xml ) Need Help??

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 (Bishop) 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;

    🦛

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11145616]
Approved by LanX
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-19 04:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found