• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regex Self Test doubt

 
Siri Naray
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
package chapter6;
import java.util.regex.*;
public 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
What is the result
A. 234
B. 334
C. 2334
D. 0123456
E. 01234456
F. 12334567
G. Compilation Fails

The answer given is E.

Can anyone pl explain why E is the answer?
When i run this prg in Eclipse IDE i dont see any answer at all. Why?
Thank you
 
Ulf Dittmer
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please check the FAQ before posting: http://faq.javaranch.com/java/ScjpFaq#kb-regexp
 
Siri Naray
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That helps but when i run this program i dont see any output. basically the control is not entering the while loop at all.
Also what is the difference between * and *? ie a greedy and reluctant quntifiers? How does the execution change if we use a *? instead of greedy??

This concept is not clear in K&B. Please help
sirisha
 
John Sutt
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably you're not feeding the command-line arguments correctly
to Eclipse. Try printing args[0] and args[1] at the start of your program.

The point is that \d* matches at every index, because \d* means 0 or more digits (and zero digits are always matched).
The start() method returns 0 1 2 4 5 6

It skips from 2 to 4 because there two digits are matched and the matcher continues at the end of the previous match.

The group() only returns 34 once, further it's empty as zero digits are matched al the time.

So, finally we get, 0 1 2 '34' 4 5 6
Hope I made it a bit more clear.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic