Aralanthir
05-06-2003, 06:45 PM
Hi everyone,
I'm currently writing a program in Java, and am having trouble with matching Regular Expressions. It works fine when I define characters, etc. to match, but I can't seem to get it to work with numbers.
What I want to do is:
- Take an input Strnig like "6x + 6 + 2"
- And then simplify it so that it becomes "6x + 8"
Which means that I need to extract the 6 + 2 and convert them to integers and then put them back into a string.
My current code:
Pattern numbers = Pattern.compile(expr);
Matcher numberm = numbers.matcher(result);
if (numberm.find())
{
String[] parts = numbers.split(result);
int total = 0;
for (int i=0;i<parts.length;i++)
{
total = total + Integer.parseInt(parts[i]);
}
String replacement = Integer.toString(total);
result = numberm.replaceAll(replacement);
}
String expr is initialized as:
String expr = "[1-100] \\+ [1-100]";
I also tried using "\d \\+ \d" to match the String, but that gave me an illegal escape sequence error for some reason.
Can anyone help?
I'm currently writing a program in Java, and am having trouble with matching Regular Expressions. It works fine when I define characters, etc. to match, but I can't seem to get it to work with numbers.
What I want to do is:
- Take an input Strnig like "6x + 6 + 2"
- And then simplify it so that it becomes "6x + 8"
Which means that I need to extract the 6 + 2 and convert them to integers and then put them back into a string.
My current code:
Pattern numbers = Pattern.compile(expr);
Matcher numberm = numbers.matcher(result);
if (numberm.find())
{
String[] parts = numbers.split(result);
int total = 0;
for (int i=0;i<parts.length;i++)
{
total = total + Integer.parseInt(parts[i]);
}
String replacement = Integer.toString(total);
result = numberm.replaceAll(replacement);
}
String expr is initialized as:
String expr = "[1-100] \\+ [1-100]";
I also tried using "\d \\+ \d" to match the String, but that gave me an illegal escape sequence error for some reason.
Can anyone help?
