开发者

Escaping special characters in Perl regex

开发者 https://www.devze.com 2023-04-05 11:15 出处:网络
I\'m trying to match a regular expression in Perl. My code looks like the following: my $source = \"Hello_[version]; Goodbye_[version]\";

I'm trying to match a regular expression in Perl. My code looks like the following:

my $source = "Hello_[version]; Goodbye_[version]";
my $pattern = "Hello_[version]";
if ($source =~ m/$pattern/) {
  print "Match found!"
}

The problem arises in that brackets indicate a character class (or so I read) when Perl tries to match the regex, and the match ends up failing. I know that I can escape the brackets with \[ or \], but that would require another block of code to go through the string and search for the brackets. Is there a way to have the brackets automatically ignored without escaping them individually?

Quick note: I can't just add the backslash, as this is just an example. In my real code, $source and $pattern are both coming 开发者_开发百科from outside the Perl code (either URIEncoded or from a file).


\Q will disable metacharacters until \E is found or the end of the pattern.

my $source = "Hello_[version]; Goodbye_[version]";
my $pattern = "Hello_[version]";
if ($source =~ m/\Q$pattern/) {
  print "Match found!"
}

http://www.anaesthetist.com/mnm/perl/Findex.htm


Use quotemeta():

my $source = "Hello_[version]; Goodbye_[version]";
my $pattern = quotemeta("Hello_[version]");
if ($source =~ m/$pattern/) {
  print "Match found!"
}


You are using the Wrong Tool for the job.

You do not have a pattern! There are NO regex characters in $pattern!

You have a literal string.

index() is for working with literal strings...

my $source = "Hello_[version]; Goodbye_[version]";
my $pattern = "Hello_[version]";
if ( index($source, $pattern) != -1 ) {
    print "Match found!";
}


You can escape set of special characters in an expression by using the following command.

expression1 = 'text with special characters like $ % ( )';

expression1 =~s/[\?\*\+\^\$\[\]\\\(\)\{\}\|\-]/"\\$&"/eg ;

#This will escape all the special characters
print "expression1'; # text with special characters like \$ \% \( \)
0

精彩评论

暂无评论...
验证码 换一张
取 消