$text_to_search = "example text with [foo] and more";
$search_string = "[foo]";
if ($text_to_search =~ m/$search_string/)
print "wee";
Run Code Online (Sandbox Code Playgroud)
请遵守以上代码.出于某种原因,我想在$ text_to_search变量中找到文本"[foo]",如果找到它则打印"wee".要做到这一点,我必须确保[和]被[和]替换,以使Perl将其视为字符而不是运算符.
我怎样才能做到这一点,而不必首先替换[
并]
用\[
和\]
使用s///
体现在哪里?
Dav*_*oss 62
用于\Q
自动显示变量中任何可能存在问题的字符.
if($text_to_search =~ m/\Q$search_string/) print "wee";
Run Code Online (Sandbox Code Playgroud)
Pla*_*ure 46
使用quotemeta
功能:
$text_to_search = "example text with [foo] and more";
$search_string = quotemeta "[foo]";
print "wee" if ($text_to_search =~ /$search_string/);
Run Code Online (Sandbox Code Playgroud)
Bor*_*nov 18
quotemeta (\Q \E)
如果你的Perl是5.16或更高版本,你可以使用,但如果你在下面你可以完全避免使用正则表达式.
例如,通过使用index
命令:
if (index($text_to_search, $search_string) > -1) {
print "wee";
}
Run Code Online (Sandbox Code Playgroud)