This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Regex Self Test doubt" Watch "Regex Self Test doubt" New topic

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() +;

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

Joined: Mar 22, 2005
Posts: 42965
Please check the FAQ before posting:
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
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:
subject: Regex Self Test doubt
It's not a secret anymore!