Jacek KwiecieĊ„ Jacek KwiecieĊ„ - 2 months ago 24
Java Question

IllegalArgumentException: Illegal group reference while replaceFirst

I'm trying to replace first occurence of

String
matching my regex, while iterating those occurences like this:

(this code is very simplified, so don't try to find some bigger sense of it)

Matcher tagsMatcher = Pattern.compile("\\{[sdf]\\}").matcher(value);

int i = 0;
while (tagsMatcher.find()) {
value = value.replaceFirst("\\{[sdf]\\}", "%" + i + "$s");
i++;
}


I'm getting
IllegalArgumentException: Illegal group reference
while executing
replaceFirst
. Why?

Answer Source

You need to escape the dollar symbol.

value = value.replaceFirst("\\{[sdf]\\}", "%" + i + "\\$s");

Illegal group reference error occurs mainly because of trying to refer a group which really won't exists.