Replacing numbers in string
The java math expression evaluator library I'm using requires hexadecimal
numbers to be prefixed with a 0x. The expression is passed as a string.
String expr = "0xAE6+0x22";
But while entering input I'd like to enter the numbers without the 0x and
then later prefix them. So I came up with an idea to extract the numbers
using regex in the string, prefix 0x and replace it.
String expr = "AE6+22";
Matcher m = Pattern.compile("[0123456789ABCDEF]{1,}").matcher(expr);
while (m.find())
expr = expr.replace(m.group(), "0x" + m.group());
I later found out that this won't work because if the expression is say
45+4, it becomes 0x0x45+0x4. How do I prevent it from replacing the
repeated numbers repeatedly?
No comments:
Post a Comment