1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Replace Symbols with Numbers in Java?

Discussion in 'Mac Programming' started by JOD8FY, Mar 21, 2007.

  1. macrumors 6502a


    Hello all,

    I have a question about how to replace symbols with numbers in Java. I know that this can be done with letters using replaceAll(), but it doesn't seem to work with symbols. What I'd like to do is convert 100.0? into 100.00. Essentially, I'm making the question mark a zero so that I can use the 100.00 to multiply, divide, etc. Here is a sample of my code (textToConvert and textConverted are both text fields):

    String line = textToConvert.getText();
    String replaced = line.replaceAll("?", "0");
    This will compile fine, but when I enter, for instance, 100.0? into the textToConvert text field, it won't function at all; nothing is converted and nothing is placed in the textConverted text field. Any help would be greatly appreciated.

  2. macrumors 6502a

    I think your problem is that repalceAll() expects a regular expression.
    You need something like:-

    replaceAll("\\?", "0");

    In a regular expression ? acts as a quantifier. To specify the character '?' you need to escape it, ie '\?', but to stop Java from interpretting the '\' as an escape sequence you need to escape the '\'… hence '\\?'.

    Hope this makes sense!

    b e n
  3. macrumors 6502a


    Worked like a charm! Thanks so much.


Share This Page