Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / September 2007

Tip: Looking for answers? Try searching our database.

With regex, accessing multiple groups under quantifiers

Thread view: 
valan.wood@gmail.com - 09 Sep 2007 21:33 GMT
In http://www.javaregex.com/RegexRecipesV1.pdf, I found a nifty little
example which illustrates what I'm trying to do:

Pattern p = Pattern.compile("(?i)((apple|orange|banana)[\\s,]*)+");
String txt = "List some fruits: apple, orange, banana";
Matcher m = p.matcher(txt);
boolean found = m.find();
System.out.println(m.group());
// Prints "apple, orange, banana"
System.out.println(m.group(1));
// Prints "banana"
System.out.println(m.group(2));
// Prints "banana"

Notice how it grabs "banana", but not "apple" or "orange".  I'm
thinking it should match all three, for a total of 6 groups.  Is there
a way to match all six without introducing a while (m.find()) loop?
Joshua Cranmer - 09 Sep 2007 23:26 GMT
> In http://www.javaregex.com/RegexRecipesV1.pdf, I found a nifty little
> example which illustrates what I'm trying to do:
[quoted text clipped - 13 lines]
> thinking it should match all three, for a total of 6 groups.  Is there
> a way to match all six without introducing a while (m.find()) loop?

Why, oh why, don't people bother to read documentation these days? I
will quote to you directly from the JavaDocs for java.util.regex.Pattern

 The captured input associated with a group is always the subsequence
that the group *most recently matched.* If a group is evaluated a second
time because of quantification then its previously-captured value, if
any, will be retained if the second evaluation fails. [ Emphasis added ]

The short answer to your question is: no.
Signature

Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.