regex for arithmetic expressions
807580Mar 1 2010 — edited Mar 10 2010Hi all,
I am new to Java. I was wondering if anyone can help me understand how regular expressions work. My problem is how to come up with a regular expression that would match a simple arithmetic expression like:
a + b + c + d
And I want to capture things by groups. I largely suspect that I should use something like:
(\\w+)(\\s\\+\\s(\\w+))*
(I use the \\s here because \\b doesn't seem to work)
would work by capturing the first word like sequence with (\\w+), and the succeeding repeats of the plus sign and another word being captured by (\\s\\+\\s(\\w+))*. Didn't work though. Can anyone tell me what's wrong and how to think of a better way of handling these sort of expressions?
The code I tried goes like:
String patt = "(\\w+)(\\s\\+\\s(\\w+))*";
String feed = "a + b + c + d";
Pattern p = Pattern.compile(patt);
Matcher m = p.matcher(feed);
/* here I want to see if the groupings work somehow*/
if(m.find()){
for(int i=0; i<=m.groupCount(); i++)
System.out.println(m.group(i));
}
Thanks