Perl正则表达式(使用变量作为包含Perl运算符的搜索字符串) [英] Perl regular expression (using a variable as a search string with Perl operator characters included)

查看:68
本文介绍了Perl正则表达式(使用变量作为包含Perl运算符的搜索字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$text_to_search = "example text with [foo] and more";
$search_string = "[foo]";

if ($text_to_search =~ m/$search_string/)
    print "wee";

请遵守上面的代码.由于某种原因,我想在$ text_to_search变量中找到文本"[foo]",如果找到,则打印"wee".为此,我必须确保将[和]替换为[和],以使Perl将其视为字符而不是运算符.

Please observe the above code. For some reason I would like to find the text "[foo]" in the $text_to_search variable and print "wee" if I find it. To do this I would have to ensure that the [ and ] is substituted with [ and ] to make Perl treat it as characters instead of operators.

如何执行此操作而不必先使用s///表达式将[]替换为\[\]?

How can I do this without having to first replace [ and ] with \[ and \] using a s/// expression?

推荐答案

使用\Q自动转义变量中可能存在问题的字符.

Use \Q to autoescape any potentially problematic characters in your variable.

if($text_to_search =~ m/\Q$search_string/) print "wee";

这篇关于Perl正则表达式(使用变量作为包含Perl运算符的搜索字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆