| Author |
How greedy is "*"? Sometimes I don't see it greedy enough
|
Firas Zuriekat
Ranch Hand
Joined: May 09, 2006
Posts: 143
|
|
How do I distinguish whether �*� qualifier is used in a greedy mode or not? Not every time regex sees the �*�, it is going to be used in a greedy mode. So that's why I ask the question. Specifically, there are 2 scenarios in the great K&B book that seem in contradiction. On page 479 (K&B book), "*" was used as a greedy qualifier. There is even an example on page 480 that shows regex greedily looks at the ENTIRE source data before making a determination of a match. But at the end of the chapter, in a test question below, the "*" was not used in the greedy mode! Read the explanation of that question for more details. import java.util.regex.*; class Regex2 { public static void main(String[] args) { Pattern p = Pattern.compile(args[0]); Matcher m = p.matcher(args[1]); boolean b = false; while(b = m.find()) { System.out.print(m.start() + m.group()); } } } And the command line: java Regex2 "\d*" ab34ef The code above shows the usage of "*" in a non-greedy mode while the one on page 480 shows that it is actually a greedy qualifier (it looks at entire source and works backwards and not from Left to Right). So how do I know what mode to assume for the SCJP exam (Left to Right processing as usual or the Greedy thing)? [ May 10, 2006: Message edited by: Firas Zureikat ] [ May 11, 2006: Message edited by: Firas Zureikat ]
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16692
|
|
There are actually two issues to deal with here. Take a look at the Java Doc for the find method... Notice that the find() method, searches for the first match, that wasn't previously matched -- regardless of the regular expression. So, while it is true that the regular expression specified states that the match must be greedy, the match required is that it is the first (next) match. This means that a smaller, less greedy, but eariler match, will be returned first. Henry [ May 10, 2006: Message edited by: Henry Wong ]
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
 |
|
|
subject: How greedy is "*"? Sometimes I don't see it greedy enough
|
|
|