简体   繁体   English

perl-在不带引号的字符串中转义特殊字符

[英]perl - escape special characters in string without quotemeta

I have a Perl string with special characters and newlines which needs to be passed to a command line utility (which does not accept special chars unless escaped). 我有一个带有特殊字符和换行符的Perl字符串,需要将其传递给命令行实用程序(除非转义,否则它将不接受特殊字符)。

How do I substitute each special character with preceding \\ ? 如何用前面的\\替换每个特殊字符?

I could substitute each char separately, but want to know whether there is a better way? 我可以分别替换每个字符,但想知道是否有更好的方法?

String comes as follows when read from a cell in a spreasheet. 从电子表格中的单元格读取时,字符串如下。

<meta property="og:url" content="http://www.example.com/test/testpage.aspx?ID=OO3JUPVSWjs%3d&ContentTypeId=qbeAILfmBIE%3d" />

I tried $str =~ /^\\Q$str\\E/; 我试过$str =~ /^\\Q$str\\E/;

but that fails when the variable is passed to the command line utility. 但是将变量传递到命令行实用程序时失败。

As you've already pointed out, you can just use quotemeta 正如您已经指出的那样,您可以只使用quotemeta

$str = quotemeta $str;

However, if that isn't good for whatever reason, you can just build your own character class of characters that you want to escape 但是,如果由于某种原因这不好,您可以构建自己的想要转义的字符类

$str =~ s/([\\'"])/\\$1/g;

You can build the pattern and perform the match separately: 您可以构建模式并分别执行匹配:

my $pattern = "$bar";
my $regex = "\Q$pattern\E";

if ( q(foo $bar baz) =~ /$regex/ ) {
    print "match\n"
}
else {
    print "no match\n"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM