Reputation: 28932
I have a string which I want to use in a regular expression it a way like m/$mystring_03/
however $mystring
contains +s and slashes that cause problems. Is there a simple way in Perl to modify $mystring
to ensure all regular expression wildcards or other special characters are properly escaped? (like all +
turned into \+
)
Upvotes: 2
Views: 1389
Reputation: 35341
If you are going to escape all special characters for regular expressions in the string you can just as well use rindex like
index($_, "$mystring_03")
this returns the index of the string in the string you want to test or -1 when no match is found.
Upvotes: 1
Reputation: 64939
Yes, use the \Q
and \E
escapes:
#!/usr/bin/perl
use strict;
use warnings;
my $text = "a+";
print
$text =~ /^$text$/ ? "matched" : "didn't match", "\n",
$text =~ /^\Q$text\E$/ ? "matched" : "didn't match", "\n";
Upvotes: 13