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