Partial regex exception

I am looking to create a template consisting of some fixed parts and a variable (actually the name of a business unit). In fact, there is a high probability that a variable contains some specific regular characters that can be recognized as controlling regular expressions (for example, + or *).

Is there any regex tag that notices that the template substructure should only be considered as text and ignore the specific char meaning?

some kind of:

regex_fixed_part [escape]business + unit[/espace] regex_fixed_part

here the business + unit will be replaced in the business \ + unit parser

Obviously, I could have manually avoided the entire char regular expression, but I'm looking for a tidier method.

thank

+3
source share
4 answers

Many regex options have a utility method that automatically escapes metacharacters. Java does this by using Pattern.quote(String), as PHP has a similar function: preg_quote(string). Many PCRE implementations also support escape sequences \Qand \E. \Qwill allow the regular expression engine to interpret all characters after it as simple literals until the next \E.

Example:

a\Q+*\Eb+

will match the string a+*bbb.

+4
source

What language?

In python:

import re
regex_fixed = re.escape("business + unit")

In php use preg_quote()

0
source

Java Pattern.quote() "\\Qprotected part\\E", .

0

[[\]\^\-\\\/?*+$().|] \$& ( , $&, ) .

0
source

Source: https://habr.com/ru/post/1728016/


All Articles