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 \+
)
views:
82answers:
3
+1
A:
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.
Peter Tillemans
2010-09-02 16:51:12
The entire regex might not be not be in the string.
Chas. Owens
2010-09-02 17:06:31
@Chas. Owens If the entire regex (after quoting) is not in the string, it is not going to match, is it? I am not following... When would a fully quoted regex give different results from a substring check?
Peter Tillemans
2010-09-02 17:17:55
Why mention `rindex` and not mention `index`?
mobrule
2010-09-02 17:22:12
@mobrule no reason, I edited it becquse there is no reason to start from the end, although AFAICS it would not matter in the problem at hand
Peter Tillemans
2010-09-02 17:34:54
@Peter Tillemans I am talking about something like this: `/(?:full)?name: \Q$name\E/`
Chas. Owens
2010-09-02 18:10:58
+11
A:
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";
Chas. Owens
2010-09-02 17:01:13