Tyzak
Tyzak

Reputation: 2436

Perl regexp how to escape only some chars

I have a string $regexp_as_string

Now I want to "convert" it into an regex / use it as regexp

if ($text_to_search =~ $regexp_as_string)
{
...
}

Now there are characters like "." and I want to automaticly escape them - \Q and \E should do that

 if ($text_to_search =~ /\Q$regexp_as_string\E/)
    {
    ...
    }

Is there a way to specify a list of characters that should be auto escaped? Because at the moment that way auto escapes for example "|" , but I want to keep that.

Upvotes: 8

Views: 1342

Answers (3)

Vorsprung
Vorsprung

Reputation: 34447

using TLP's example string

my $str='foo${}|';
$str =~ s/([\.\{\}\$])/\\$1/g;
print $str;

This will ONLY add a backslash to characters that are in the square brackets "character class"

Note that I've put a blackslash in front of the characters in the square brackets. This isn't always necessary for all characters in this context but it's easier to just add a backslash and not worry about it.

Upvotes: 0

MkV
MkV

Reputation: 3096

Perhaps instead of passing a string joined by | for alternations, get the list of alternations and build them up into a string (or even split them by | if that is guaranteed to never appear)? Something like:

my @alternations = array_returning_function();
# my @alternations = split(/\|/, string_returning_function());
my $regexp_as_string = join('|', map(quotemeta, @alternations)); 

or use Data::Munge's list2re function:

use Data::Munge;
my @alternations = array_returning_function();
# my @alternations = split(/\|/, string_returning_function());
my $regexp_as_string = Data::Munge::list2re( @alternations );

Upvotes: 0

TLP
TLP

Reputation: 67920

You can prepare the string using quotemeta, then remove backslashes selectively. E.g.:

my $str = quotemeta('foo${}|'); 
$str =~ s/\\(?=[|])//g; 
say $str;

Output:

foo\$\{\}|

Add any characters you want not escaped to the character class in the substitution, e.g. [|?()].

Upvotes: 14

Related Questions