开发者

Making Strings Safe for Regular Expressions in Perl

I have a string which I want to use in a regular expression it a way like m/$mystring_03/ however $mystring co开发者_StackOverflow中文版ntains +s and slashes that cause problems. Is there a simple way in Perl to modify $mystring to ensure all regular expression wildcards or other special characters are properly escaped? (like all + turned into \+)


Yes, use the \Q and \E escapes:

#!/usr/bin/perl

use strict;
use warnings;

my $text = "a+";

print
    $text =~ /^$text$/     ? "matched" : "didn't match", "\n",
    $text =~ /^\Q$text\E$/ ? "matched" : "didn't match", "\n";


The quotemeta function does what you are asking for.


If you are going to escape all special characters for regular expressions in the string you can just as well use rindex like

index($_, "$mystring_03")

this returns the index of the string in the string you want to test or -1 when no match is found.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜