在Perl中使正则表达式的字符串安全

dor*_*ron 2 regex perl

我有一个字符串,我想在正则表达式中使用它,m/$mystring_03/但是$mystring包含导致问题的+ s和斜杠.是否有一种简单的方法在Perl中进行修改$mystring以确保所有正则表达式通配符或其他特殊字符都被正确转义?(就像所有人都+变成了\+)

Cha*_*ens 13

是的,使用\Q\E转义:

#!/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";
Run Code Online (Sandbox Code Playgroud)


Pet*_*sel 10

quotemeta功能做你所要求的.