Web Hosting Talk







View Full Version : Java Regular Expression Matching


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?

ilyash
05-06-2003, 07:30 PM
can u include more of your code?

Aralanthir
05-06-2003, 07:32 PM
That's pretty much all the relevant code. The code before basically strips out anything that has "+0" in it and that part has been tested and works. I'm basically left with code like "5 + 6" when I try to use the code I posted.

Do you think I'm missing something important?

ilyash
05-06-2003, 07:38 PM
number format exception somewhere...

rooshine
05-06-2003, 07:43 PM
You can only match [0-9], not [0-100], so you would have to match [0-9][0-9][0-9] for three digits, or:

[0-9]*?

It's been a little while since I worked on regular expressions, but I believe that means a digit 1 or more times.

rooshine
05-06-2003, 07:48 PM
Sorry, I think the above code means zero or more times. Try [0-9]+

jb4mt
05-06-2003, 08:24 PM
\d stands for a digit, its much more compact than [0-9], though I often like to use the latter when I want to make sure, for instance, that I don't have a leading zero, then I will use the range [1-9]