Escaping special characters in Perl regex

﹥>﹥吖頭↗ 提交于 2019-12-30 08:52:49

问题


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).


回答1:


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!";
}



回答2:


\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




回答3:


Use quotemeta():

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



回答4:


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 \$ \% ( )



来源:https://stackoverflow.com/questions/7423143/escaping-special-characters-in-perl-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!