Svetlin Zarev Svetlin Zarev - 3 months ago 14
Java Question

Escaping set of character by using a single regular expression

I have a set of characters:

that are considered as "reserved" and all occurrences must be escaped. How can I do that using a single regex ?

This needs to be done using a single regex, because running a
for each of the characters in the reserved set greatly reduces the performance.

For instance
escape(I | have \ a dog #)
should yield the result "I \| have \\ a dog \#".


Following @neuhaus answer: The regex is
and the replacement is


write a regexp that matches the characters you want.

Example: /([|#\\])/

Replace them with the escape character followed by the matched character.