Java

Java Lesson for the Day

I am not sure how this bug got through our first round of testing but I have some code which looks like this...

String source = "The BNL";
String pattern = "If I had $1000000";
System.out.println(source.replaceAll(source, pattern));

I was getting an error of "java.lang.IndexOutOfBoundsException: No group 1". The astute amongst you will notice that this will never work as $ is a heavily used regex character. So what to do, either I could manually escape the pattern string, but that gets us into a whole hellish world of backslashes. So instead enter a static method that I hadn't tried before... Matcher.quoteReplacement().

What it does is escape the pattern string for me before then being used in the replaceAll process. So my fixed code looks like this:

String source = "The BNL";
String pattern = "If I had $1000000";
System.out.println(source.replaceAll(source, Matcher.quoteReplacement(pattern)));

Not a big thing but it had me scratching my head for a while this afternoon, so thought I'd write it down for future reference.