본문 바로가기

emotional developer/detect-Java

java.lang.IllegalArgumentException: Illegal group reference

http://tech.soronthar.com/2007/12/javalangillegalargumentexcepti.html

I was doing some regexp work on one of my projects, when suddenly this well-known and hundred-of-times implemented code right from the javadoc, failed:

   StringBuffer result = new StringBuffer(text.length());
   while (includeMatcher.find()) {
      String includeFile = includeMatcher.group(1);
      String s = readTemplate(includeFile, area,topic,skins,false);
      includeMatcher.appendReplacement(result, s);
   }
   includeMatcher.appendTail(result);
   text = result.toString();


A java.lang.IllegalArgumentException was thrown.

Thanks to google, I found out what happened: There was a $ sign in the replacement string. 
Now, of course this was mentioned in the Matcher javadoc but nowhere in the documentation is stated that an IllegalArgumentException will be thrown.

Just for the record: the solution I implemented was to insert the following line just before the appendReplacement call:


s=s.replaceAll("\\$","\\\\\\$")


Hope this post helps someone in the future.

Update: One commenter gave another solution:

Since Java 1.5 you can do

s = Matcher.quoteReplacement(s)

 
반응형

'emotional developer > detect-Java' 카테고리의 다른 글

eclipse reverse engineering plugin  (0) 2014.01.06
6 Java Libararies to save your Time  (0) 2011.06.26
Top 5 free Java ebooks  (0) 2011.06.26