Javas String.replaceAll

July 21, 2009 by Michael

The following statement

"foo baz".replaceAll("baz","$bar");

will present you an java.lang.IllegalArgumentException: Illegal group reference exception as the replacement string can contain backreferences to the search pattern as stated in Mather#replaceAll:

This method first resets this matcher. It then scans the input sequence looking for matches of the pattern. Characters that are not part of any match are appended directly to the result string; each match is replaced in the result by the replacement string. The replacement string may contain references to captured subsequences as in the appendReplacement method.

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. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

Luckily, there is an easy solution:

"foo baz".replaceAll("baz",Matcher.quoteReplacement("$bar"));

No comments yet

Post a Comment

Your email is never published nor shared. Required fields are marked *