I am in need to replace
\\\s+\\$\\$ to $$
I used
String s = " $$"; s = s.replaceAll("\\s+\\$\\$","$$");
but it throws exception
java.lang.IllegalArgumentException: Illegal group reference
The replaceAll() method is similar to the String. replaceFirst() method. The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string.
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement .
\\s+ --> replaces 1 or more spaces. \\\\s+ --> replaces the literal \ followed by s one or more times.
replaceAll() The method replaceAll() replaces all occurrences of a String in another String matched by regex. This is similar to the replace() function, the only difference is, that in replaceAll() the String to be replaced is a regex while in replace() it is a String.
From String#replaceAll javadoc:
Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.
So escaping of an arbitrary replacement string can be done using Matcher#quoteReplacement:
String s = " $$"; s = s.replaceAll("\\s+\\$\\$", Matcher.quoteReplacement("$$"));
Also escaping of the pattern can be done with Pattern#quote
String s = " $$"; s = s.replaceAll("\\s+" + Pattern.quote("$$"), Matcher.quoteReplacement("$$"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With