1

I am able to replace regex character to blank with the following code:

str = str.replaceAll('\\p{Punct}', ''); System.debug(LoggingLevel.DEBUG, '***str: ' + str);

Here is the reference that I got the above code: Regex Help- Escaping Characters And Matcher Method

But how to add the escape character and not replace it to blank?

for example:

"This is the string [the-string] that will be replaced with escape character in regex"

what I want:

"This is the string \[the\-string\] that will be replaced with escape character in regex"

How can I achieve this?

EDIT

I tried using

String str = 'This is the string [the-string] that will be replaced with escape character in regex';
str = str.replaceAll('\\p{Punct}', '\\$&');
System.debug(LoggingLevel.DEBUG, '***str: ' + str);

But the output is:

***str: This is the string $&the$&string$& that will be replaced with escape character in regex

1 Answer 1

4

Use $0 to include the matched expression in the replacement. As mentioned in the prior answer, you need to double-escape the escape character to get a literal escape character to the regexp engine, and you need to escape the escape character to get a literal escape character in the resulting string, for a total of four escape characters (\\\\). The resulting code looks like this:

String str = 'This is the string [the-string] that will be replaced with escape character in regex';
str = str.replaceAll('\\p{Punct}', '\\\\$0');
System.debug(LoggingLevel.DEBUG, '***str: ' + str);

Output:

[3]|DEBUG|***str: This is the string \[the\-string\] that will be replaced with escape character in regex

Not the answer you're looking for? Browse other questions tagged .