Nano HE
Nano HE

Reputation: 9307

How do I match "/*" in a regex?

$stuff = "d:/learning/perl/tmp.txt";

open STUFF, $stuff or die "Cannot open $stuff for read :$!";
while (<STUFF>) {
    my($line) = $_; # Good practice to always strip the trailing
    chomp($line);
    my @values = split(' ', $line);

    foreach my $val (@values) {

        if ($val == 1){
            print "1 found";    
        }
        elsif ($val =~ /hello/){
            print "hello found";    
        }
        elsif ($val =~ /"/*"/){ # I don't know how to handle here.
            print "/* found";    
        }
        print "\n";
    }
}

My tmp.txt:

/* CheerStone ColdStunner 

1 Cheer Rock

hello Boo Pedigree

How do I handle the /* character sequence in my code?

Upvotes: 4

Views: 816

Answers (3)

brian d foy
brian d foy

Reputation: 132896

There are various ways to un-meta regex metacharacters. In your case, you need to handle the character that is the default delimiter as well as a meta-character.

  • In the case of a delimiter character that you want to be a literal character, you can escape that character with \, although you can get leaning toothpick syndrome:

    m/\/usr\/local\/perls/;
    
  • You can change the delimiter:

    m(/usr/local/perl);
    
  • You can escape meta-characters in the same way:

    m(/usr/local/perl\*);
    
  • If you want a section of your pattern to be only literal characters, you can use \Q to automatically escape them for you:

    m(\Q/usr/local/perl*);
    
  • If you want a smaller section of your pattern to be only literal characters, you can use \Q then turn it off with \E:

    m(/usr/local/perl\Q*+?\E/);
    
  • The \Q is really the same thing as quotemeta. Putting your pattern into a variable then interpolating it in the match operator also solves the delimiter problem:

    my $pattern = quotemeta( '/usr/local/perl*+?/' );
    m/$pattern/;
    

Upvotes: 12

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74262

The * is a special character. So, you have to escape it:

m{/\*}

As Adam Bellaire has suggested, here is a brief explanation:

Picket-fences are best avoided. For that, sometimes, delimiters other than / have to be used. m should precede the first delimiter when using such delimiters. If any of the brackets are used as the first delimiter, the corresponding closing bracket has to be used as the end delimiter.

Upvotes: 16

Luk&#225;š Lalinsk&#253;
Luk&#225;š Lalinsk&#253;

Reputation: 41316

Both characters have special meaning in Perl regular expression, so you have to escape them with a backslash:

$val =~ /\/\*/

Btw, you should probably add ^ in front of all the regexes, because you seem to want to handle only text on the beginning of the line.

Upvotes: 8

Related Questions