wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Regex Self Test doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Regex Self Test doubt" Watch "Regex Self Test doubt" New topic
Author

Regex Self Test doubt

Siri Naray
Ranch Hand

Joined: May 19, 2006
Posts: 105
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


If you worry you cannot work... If you work you need not worry
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 39535
    
  27
Please check the FAQ before posting: http://faq.javaranch.com/java/ScjpFaq#kb-regexp


Ping & DNS - updated with new look and Ping home screen widget
Siri Naray
Ranch Hand

Joined: May 19, 2006
Posts: 105
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

Joined: Mar 07, 2008
Posts: 42
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.


SCJP 6 (91%), SCJD (91%)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regex Self Test doubt
 
Similar Threads
Regex Question
Java command-line input argument??
kb p. 498
SCJP 6 : Chapter 6 p.515 Self Test Question 1
Chapter 6 Self Test Q1