tags:

views:

63

answers:

4

Hello,

I search to built a pattern composed by some fixed parts and a variable (in reality Business Unit name). In fact, there is high chance that the variable contains some specific regex characters which can be recognize as regex control ones (i.e + or *).

Is there any regex tag that notice that a pattern subpart should be considered only as text, and ignore specific char meaning?

some kind of :

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

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

Obviously, I could escape manually all regex char, but I search a more tidy method.

Thanks

A: 

What language?

In python:

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

In php, use preg_quote()

Kimvais
in PHP, preg_quote() should be used
duckyflip
No, in PHP you should use `preg_quote`. `addslashes` is used for escape strings used in SQL.
Bart Kiers
Thanks, corrected
Kimvais
A: 

In Java, use Pattern.quote() or "\\Qprotected part\\E" if you want to do it manually.

Aaron Digulla
+3  A: 

Many regex flavors have a utility method that automatically escapes meta characters. Java does this using Pattern.quote(String) and PHP has a similar function: preg_quote(string). Many PCRE implementations also support the \Q and \E escape sequences. \Q will let the regex engine interpret all characters after it as plain literals until the next \E.

Example:

a\Q+*\Eb+

will match the string a+*bbb.

Bart Kiers
it was exactly what I was searching for (too bad I did not found it by myself), unfortunately, seems not be recognize in C# |ArgumentException : Unrecognized escape sequence \Q.
camous
Then you're out of luck. According http://www.regular-expressions.info/characters.html, only the JGsoft engine, Perl, PHP and Java support `\Q..\E`. Looks like you will need Regex.Escape (as you yourself already mentioned).
Bart Kiers
@camous - this isn't supported by .net according to http://www.regular-expressions.info/refflavors.html . Presumably, you'll have to build the string anyway, so `Regex.Escape` doesn't complicate it too much.
Kobi
Yes finaly I use Regex.Escape for this purpose. will be ok but a bit disapointed of this lacking functionnality. thanks
camous
A: 

Replace [[\]\^\-\\\/?*+$().|] with \$& (backslash followed by $&, the matched string) with the global flag on.

Amarghosh