Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 722
Tyzak Avatar asked Feb 11 '12 11:02

Tyzak


People also ask

How do I escape characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

How do I escape a character in Perl?

The backslash is the escape character and is used to make use of escape sequences. When there is a need to insert the escape character in an interpolated string, the same backslash is used, to escape the substitution of escape character with ” (blank). This allows the use of escape character in the interpolated string.

What is \d in Perl regex?

The Special Character Classes in Perl are as follows: Digit \d[0-9]: The \d is used to match any digit character and its equivalent to [0-9]. In the regex /\d/ will match a single digit. The \d is standardized to “digit”.

How do you escape a forward slash in regex?

You escape it by putting a backward slash in front of it: \/ For some languages (like PHP) you can use other characters as the delimiter and therefore you don't need to escape it. But AFAIK in all languages, the only special significance the / has is it may be the designated pattern delimiter.


1 Answers

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. [|?()].

like image 168
TLP Avatar answered Oct 03 '22 09:10

TLP