CoV
CoV

Reputation: 105

Escaping special characters in Perl regex

I'm trying to match a regular expression in Perl. My code looks like the following:

my $source = "Hello_[version]; Goodbye_[version]";
my $pattern = "Hello_[version]";
if ($source =~ m/$pattern/) {
  print "Match found!"
}

The problem arises in that brackets indicate a character class (or so I read) when Perl tries to match the regex, and the match ends up failing. I know that I can escape the brackets with \[ or \], but that would require another block of code to go through the string and search for the brackets. Is there a way to have the brackets automatically ignored without escaping them individually?

Quick note: I can't just add the backslash, as this is just an example. In my real code, $source and $pattern are both coming from outside the Perl code (either URIEncoded or from a file).

Upvotes: 7

Views: 13334

Answers (4)

emmanuelgws
emmanuelgws

Reputation: 69

You can escape set of special characters in an expression by using the following command.

expression1 = 'text with special characters like $ % ( )';

expression1 =~s/[\?\*\+\^\$\[\]\\\(\)\{\}\|\-]/"\\$&"/eg ;

#This will escape all the special characters
print "expression1'; # text with special characters like \$ \% \( \)

Upvotes: 0

martincho
martincho

Reputation: 4717

\Q will disable metacharacters until \E is found or the end of the pattern.

my $source = "Hello_[version]; Goodbye_[version]";
my $pattern = "Hello_[version]";
if ($source =~ m/\Q$pattern/) {
  print "Match found!"
}

http://www.anaesthetist.com/mnm/perl/Findex.htm

Upvotes: 14

tadmc
tadmc

Reputation: 3744

You are using the Wrong Tool for the job.

You do not have a pattern! There are NO regex characters in $pattern!

You have a literal string.

index() is for working with literal strings...

my $source = "Hello_[version]; Goodbye_[version]";
my $pattern = "Hello_[version]";
if ( index($source, $pattern) != -1 ) {
    print "Match found!";
}

Upvotes: 12

Pedro Silva
Pedro Silva

Reputation: 4700

Use quotemeta():

my $source = "Hello_[version]; Goodbye_[version]";
my $pattern = quotemeta("Hello_[version]");
if ($source =~ m/$pattern/) {
  print "Match found!"
}

Upvotes: 13

Related Questions