If you're using JDK 5, you can also use
The difference between replace() and replaceAll() is not obvious from the name - actually replace() replaces all occurrances of whatever you're replacing, much like replaceAll(). The real difference is that replace() is simple and does exacly what you'd expect it to do, while replaceAll() has more complex behavior.
Warning - the following is a bit outside the scope of the "Beginner" forum, so some of you may just want to skip this post. But it does follow directly from the preceding conversation.
[EFH]: The second argument is a regular expression, The
first argument is a
regular expression (though that doesn't happen to create any problems in this particular case since a / is not a special character for Java regular expressions). The second argument is
not a regular expression, but a replacement string - which has its own rules, much simpler than a regular expression, but hard to find in the documentation. The clearest explanation to be found in the API (after following several intermediate links) is in the
Matcher class, under the appendReplaceMent() method. Basically, in a replacement string, \ and $ characters have special significance, so if you want a "plain" \ or $, you have to insert an extra \ in front. And in a Java literal each \ must be doubled to \\. As previously noted.
In JDK 5 they added the replace() method show above, which is much simpler to use. Also there are two static methods which can be used to escape any special characters in a given expression, so that you get a string that "means" the same thing as the original literal string would have (if not for special characters).
Pattern.quote(str) - use this for a value that can be used as a regular expression
Matcher.quoteReplacement(str) - use this for a value that can be used as a replacement string
In other words, if str, x, and y are Strings, then
is equivalent to
Obviously the first form is easier to read - the second form just shows who the methods are related.
[ December 06, 2005: Message edited by: Jim Yingst ]