String replaceAll() and regex question

Discussion in 'Java' started by grasp06110, May 28, 2006.

  1. grasp06110

    grasp06110 Guest

    Hi All,

    I would like to hand the replaceAll() method of String text that it
    would interpret as literal text and not as a regex. In the code I am
    trying to implement I am given two variables and a string and need to
    replace one variable with the second in the string. If either of the
    variables contains a special character (e.g. $) the replaceAll() method
    can fail. An example of this is shown below. In the example below I
    can escape the $ character with /$ but I don't want to have to search
    each string for every potential trouble maker. I would like to tell
    the regex to treat the entire string as a literal.

    Any help would be appreciated.


    public class Ouch {

    public static void main(String[] args) throws Exception {
    String start = "yours now for just <amount>";
    String price = "$9.99";
    String end = start.replaceAll("<amount>", price);


    Exception in thread "main" java.lang.IndexOutOfBoundsException: No
    group 9
    at java.util.regex.Matcher.appendReplacement(
    at java.util.regex.Matcher.replaceAll(
    at java.lang.String.replaceAll(
    at Ouch.main(
    grasp06110, May 28, 2006
    1. Advertisements

  2. wrote in
    What you probably want to use is actually String.replace(). The name is
    unfortunate - it replaces more than one occurence, even if it is easy to
    believe otherwise by just seeing the name (together with replaceAll()). see
    the API for more info.
    Martin Gerner, May 28, 2006
    1. Advertisements

  3. Hm, the link got bogged up. Well, just scroll down until you get on
    Martin Gerner, May 28, 2006
  4. grasp06110

    Chris Smith Guest

    Yep. See the static methods Pattern.quote and Matcher.quoteReplacement.

    The Easiest Way To Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
    Chris Smith, May 28, 2006
  5. Hi John!!
    I am not sure why this is not working. But have you tried this with
    g.rajeshchowdary, May 28, 2006
  6. grasp06110

    grasp06110 Guest


    Martin Gerner's suggestion of using String.replace looks like it should
    work. My bad for not looking at the api more closely.

    grasp06110, May 28, 2006
  7. grasp06110

    Bernd Klier Guest

    You have to escape the '$' character. Try
    String price = "\\$9.99";
    and it'll work for you.


    Bernd Klier, May 29, 2006
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.