Perl regular expression (using a variable as a search string with perl operator characters included)

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

Please follow the code above. For some reason, I would like to find the text "[foo]" in the variable $ text_to_search and print "wee" if I find it. For this, I would have to make sure that [and] is replaced by [and] so that Perl treats it as characters instead of operators.

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

+44
regex perl
Jan 06 2018-11-11T00:
source share
3 answers

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

 if($text_to_search =~ m/\Q$search_string/) print "wee"; 
+49
Jan 06 2018-11-18T00:
source share
— -

Use the quotemeta function:

 $text_to_search = "example text with [foo] and more"; $search_string = quotemeta "[foo]"; print "wee" if ($text_to_search =~ /$search_string/); 
+44
Jan 6 2018-11-11T00:
source share

As the guys have already written, you can use quotemeta (\Q \E) if your Perl is 5.16+, but if below you can simply not use regexp at all.

for example using the index command

 if (index($text_to_search, $search_string) > -1){ print "wee"; } 
+13
Jul 30 '14 at 17:56
source share



All Articles