Svetlin Zarev Svetlin Zarev - 1 year ago 63
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

Answer Source

write a regexp that matches the characters you want.

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download