Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in K&B Book.

 
Pankaj Shet
Ranch Hand
Posts: 293
Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
This is the question in K&B's book.According to me the answer should be 234 i.e.Option A.
However, in this book the explaination is given as follows.

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.
And also A, B, C, D, E, F, and G are incorrect based on the above.
E is included in the incorrect options too.

So there is no way to understand the correct option or the answer.
Given:

import java.util.regex.*;
class Regex2 {
public static void main(String[] args) {
Pattern p = Pattern.compile(args[o]);
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.


- Thank you.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"According to me the answer should be 234 i.e.Option A."

Nope. Did you run the program with the provided input? If you did, then you would get 01234456 which is the correct answer E. The fact that the text includes E in the list of incorrect answers is a typo error that has been noticed before by several other ranchers.

To understand why the answer is 01234456 check out our FAQ here.
 
Pankaj Shet
Ranch Hand
Posts: 293
Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sir/madam,
I got the answer. Thanks for reply.
I did'nt run the program before.
Sorry.
-thank you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic