Sunday, May 30, 2010

java.lang.IllegalArgumentException: Illegal group reference

"java.lang.IllegalArgumentException: Illegal group reference"

Not a very frequent exception encountered by the developers, but when encountered than they are mad as its not their fault but it is due to the fact that one more character is been assumed as Special by java folks.

When it Occurs:-

Use of the following functions of String class and the second argument to these functions contains "$" cause the exception

  1. public String replace(CharSequence target, CharSequence replacement)
  2. public String replaceAll(String regex, String replacement)
Why is Happens: -

repalce and replaceAll() functions use the "appendReplacement()" method (defined in String class) and $ has been treated as back reference
Each occurrence of $g will be replaced by the result of evaluating group(g), where g must be a number between '0' and '9' (i.e. a valid capturing group number).

Solution: -

Replace "$" with "\\$" and it will work but take care that you use "replace(CharSequence, CharSequence)" in order to replace "$".

"replace(CharSequence, CharSequence)" unlike replaceAll() doesnt uses pattern matching.

No comments: