Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

regex for arithmetic expressions

807580Mar 1 2010 — edited Mar 10 2010
Hi 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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 7 2010
Added on Mar 1 2010
11 comments
2,617 views