Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does replaceAll fail with "illegal group reference"?

Tags:

java

regex

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

like image 508
Sathish Kumar k k Avatar asked Aug 11 '12 10:08

Sathish Kumar k k


People also ask

What is the difference between replaceAll and replace?

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.

What do the replaceAll () do?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement .

What does replaceAll \\ s+ do?

\\s+ --> replaces 1 or more spaces. \\\\s+ --> replaces the literal \ followed by s one or more times.

Does replaceAll use regex?

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.


1 Answers

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("$$")); 
like image 86
Andrey Avatar answered Sep 28 '22 20:09

Andrey