Svetlin Zarev Svetlin Zarev - 1 month ago 6
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
replaceAll()
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 \#".

Solution



Following @neuhaus answer: The regex is
([\\|#])
and the replacement is
\\$0

Answer

write a regexp that matches the characters you want.

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

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