yegor256
yegor256

Reputation: 105213

How to escape a regular expression when I include it in another regular expression?

I'm trying to use a string as a regular expression inside another regular expression:

my $e = "a+b";
if ('foo a+b bar' =~ /foo ${e} bar/) {
    print 'match!';
}

Doesn't work, since Perl treats + as a special character. How do I escape it without changing the value of $e?

Upvotes: 3

Views: 63

Answers (1)

Shawn
Shawn

Reputation: 52644

You can use \Q and \E, which treats regexp metacharacters between them as literals:

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/say/;

my $e = "a+b";
if ('foo a+b bar' =~ /foo \Q$e\E bar/) {
    say 'match!';
}

Upvotes: 5

Related Questions