Jacek KwiecieĊ„ Jacek KwiecieĊ„ - 7 months ago 62
Java Question

IllegalArgumentException: Illegal group reference while replaceFirst

I'm trying to replace first occurence of

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'm getting
IllegalArgumentException: Illegal group reference
while executing
. 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download