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)


No TrackBacks

TrackBack URL: http://tech.soronthar.com/mt/mt-tb.cgi/39

7 Comments

| Leave a comment

Thank you! I had the same problem

Man! Thanks! You just saved me my deadline!

You rock, thanks so much for posting this! I suspected it was the '$' but this example saved me loads of testing time.

user-pic

It works, but it turns all capture groups into literal strings.

I want "hello" to be turned into "<B>hello</B>", so I use this replacement string: "<B>$1</B>", but with your solution, it RESULTS in "<B>$1</B>".

Thanks man; saved hours of pain and suffering!

I'm quite late but as this post is one of the first returned by Google I provide my own two cents.

Since Java 1.5 you can do

s = Matcher.quoteReplacement(s)

Hope this could help.

Thaks! I'll update the post accordingly

Leave a comment

About this Entry

This page contains a single entry by Soronthar published on December 29, 2007 6:38 PM.

Newbie ScribeFire tip was the previous entry in this blog.

Java Quirks: ListSelectionListener is always called more than once is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.