aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes SCJP book regex, pattern and matcher question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "SCJP book regex, pattern and matcher question" Watch "SCJP book regex, pattern and matcher question" New topic
Author

SCJP book regex, pattern and matcher question

subathra sangameswaran
Greenhorn

Joined: Nov 19, 2005
Posts: 27
Hi Everyone,
Following is one question from K&B SCJP 5 book.
I don't understand how this e answer is correct.
Given:
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
What is the result?
A. 234
B. 334
C. 2334
D. 0123456
E. 01234456
F. 12334567
G. Compilation fails.
Answer:
� 3 E is correct. The \d is looking for digits. The * is a quantifier that looks for 0 to many occurrences of the pattern that precedes it. Because we specified *, the group() method returns empty Strings until consecutive digits are found, so the only time group() returns a value is when it returns 34 when the matcher finds digits starting in position 2. The
start() method returns the starting position of the previous match because, again,we said find 0 to many occurrences.

Once at index 2, group brings 34. How come the rest of the result is arrived. Only until 5 are the index available, and if it prints empty strings again, how come it gets to 56 in the end?
Thanks and regards,
Subha.
[ February 27, 2006: Message edited by: subathra sangameswaran ]

suba
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 35237
    
    7
A very similar question was asked just last week.


Android appsImageJ pluginsJava web charts
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: SCJP book regex, pattern and matcher question
 
Similar Threads
K & B book- chapter 6 - excercie1-not able to understand
K&B Study Guide for Java 5 p498 Selftest problem 1
Regex Doubt
can some one explain me the output of this program?
Doubt in K&B Book.