如何在不解释元字符的情况下将变量用于正则表达式模式? [英] How can I use a variable for a regex pattern without interpreting meta characters?
问题描述
$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";
更新:为了阐明这是如何工作的...
Update: To clarify how this works...
\Q
将打开自动转义";正则表达式中的特殊字符.这意味着任何在匹配运算符中具有特殊含义的字符(例如,*
、^
或 [
和 ]
) 将在它们之前插入一个 \
以关闭它们的特殊含义.
The \Q
will turn on "autoescaping" of special characters in the regex. That means that any characters which would otherwise have a special meaning inside the match operator (for example, *
, ^
or [
and ]
) will have a \
inserted before them so their special meaning is switched off.
自动转义一直有效,直到发生两种情况之一.在字符串中找到 \E
或到达字符串末尾.
The autoescaping is in effect until one of two situations occurs. Either a \E
is found in the string or the end of the string is reached.
在我上面的例子中,没有必要关闭自动转义,所以我省略了 \E
.如果稍后需要在正则表达式中使用正则表达式元字符,则需要使用 \E
.
In my example above, there was no need to turn off the autoescaping, so I omitted the \E
. If you need to use regex metacharacters later in the regex, then you'll need to use \E
.
这篇关于如何在不解释元字符的情况下将变量用于正则表达式模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!