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.
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).
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.
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”.
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.
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. [|?()]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With