doron
doron

Reputation: 28932

Making Strings Safe for Regular Expressions in Perl

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

Answers (3)

Peter Tillemans
Peter Tillemans

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

Peter S. Housel
Peter S. Housel

Reputation: 2659

The quotemeta function does what you are asking for.

Upvotes: 11

Chas. Owens
Chas. Owens

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

Related Questions