Perl正则expression式(使用variables作为searchstring,包括perl运算符字符)

$text_to_search = "example text with [foo] and more"; $search_string = "[foo]"; if($text_to_search =~ m/$search_string/) print "wee"; 

请遵守上面的代码。 出于某种原因,我想在$ text_to_searchvariables中find文本“[foo]”,如果find它,则输出“wee”。 要做到这一点,我必须确保[和]被replace为[和]使perl把它当作字符而不是操作符。

问题:如何在不必首先用s///expression式replace[]情况下执行此操作?

使用\Q自动隐藏variables中可能存在问题的字符。

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

使用quotemeta函数:

 $text_to_search = "example text with [foo] and more"; $search_string = quotemeta "[foo]"; print "wee" if ($text_to_search =~ /$search_string/); 

正如你已经写的,你可以使用quotemeta (\Q \E)如果你的Perl是5.16+,但如果下面你可以简单地避免使用正则expression式。

例如通过使用index命令

 if (index($text_to_search, $search_string) > -1){ print "wee"; }