Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regex Issue

 
Luke Shannon
Ranch Hand
Posts: 239
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We have this line of code:



If current.getDescripton() returns a string that contains a $ characher I get the following error:

java.lang.IndexOutOfBoundsException: No group 2

How can this be avoided?

Luke
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're using JDK 1.5, you can use Matcher.quoteReplacement(String) to escape the special characters in the replacement string (i.e., dollar sign and backslash). Otherwise, you can do it yourself:
 
Luke Shannon
Ranch Hand
Posts: 239
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Alan!
 
Kai Witte
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,

prior to 1.5 the best way to quote a String in such a situation was to put it in \Q and \E, like that:
"\\Q{...}\\E"

Conan
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to clarify, Conan, what you're talking about is quoting the regex, which is the first argument to replaceAll(). It doesn't work for the second argument, the replacement string. As of JDK 1.5, you can use the Pattern.quote() method to quote the regex, and Matcher.quoteReplacement() to quote the replacement string.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic