tags:

views:

82

answers:

3

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 \+)

+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
The entire regex might not be not be in the string.
Chas. Owens
@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
Why mention `rindex` and not mention `index`?
mobrule
@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
@Peter Tillemans I am talking about something like this: `/(?:full)?name: \Q$name\E/`
Chas. Owens
+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
+9  A: 

The quotemeta function does what you are asking for.

Peter S. Housel
`quotemeta` is the function interface to the `\Q` and `\E` escapes.
Chas. Owens