This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Java regular expression grouping Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java regular expression grouping" Watch "Java regular expression grouping" New topic

Java regular expression grouping

Mitch Christensen

Joined: Mar 18, 2005
Posts: 3

Given the following regex pattern: "(?:\\D*(\\d+)\\D*)*"

and the following test cases: "12345" "a1234" "12a34" "1234a"

I expect to see each test case result in a set of groups that maintain the original character order, and exclude any non-digit characters.

My fallback is to iterate through the string char-by-char and build a new string skipping over non-numeric characters, but I am curious why this doesn't work for "12a34". In stead of returning the three groups "12a34" "12" "34", it returns "12a34" "34".

Where did the "12" group go?

Carol Enderlin
Ranch Hand

Joined: Oct 10, 2000
Posts: 1364
If you're just trying to pull out the digits maybe you should simplify.

Pattern: (\d+) string=12345
matched: 12345
Pattern: (\d+) string=a1234
matched: 1234
Pattern: (\d+) string=12a34
matched: 12
matched: 34
Pattern: (\d+) string=1234a
matched: 1234
Pattern: (\d+) string=1234512345
matched: 1234512345
Pattern: (\d+) string=a1234a5234
matched: 1234
matched: 5234
Pattern: (\d+) string=a1234a5234
matched: 1234
matched: 5234
Pattern: (\d+) string=1234a5234a
matched: 1234
matched: 5234
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I use a tool called RegExCoach that can step through the groups and highlight them one at a time. You can interactively tweak your expressions and see how they respond. See it here: This kind of experimentation is a fun way to learn.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Carol Enderlin
Ranch Hand

Joined: Oct 10, 2000
Posts: 1364
Thanks Stan. I'm gonna check it out.
jQuery in Action, 2nd edition
subject: Java regular expression grouping
Similar Threads
toString()class Test {
Resolving Boolean Expression
Numeric and Integer value? Same?
Regular expression to check for specific special characters (any repitition) and 0 to 9 numbers
Converting Char array to String