PDA

View Full Version : Replace Symbols with Numbers in Java?




JOD8FY
Mar 21, 2007, 04:18 PM
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):


if(e.getSource()==convert)
{
String line = textToConvert.getText();
String replaced = line.replaceAll("?", "0");
textConverted.setText(replaced);
}

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.

Thanks,
JOD8FY



lazydog
Mar 21, 2007, 04:40 PM
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

JOD8FY
Mar 21, 2007, 05:47 PM
Worked like a charm! Thanks so much.

JOD8FY