• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Patter and Matcher..Mock Question Doubt

 
Hardik Raja
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Friends,

This is Question for K & B book...Chap 6 : Page 508



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:

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.

A, B, C, D, E, F, and G are incorrect based on the above.

My question is...I am not getting how the last digit(6) is getting printed in E??

index position.......012345
Actual String........ab34ef

and what I fell the output should be is 0123445??

Can anyone please give their suggestions on the above problem.Thank you in advance.

Regards,
Hardik.S.Raja
 
anil kumar
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Hardik


A String object contains one empty string at the end.And your pattern is "\d*".Here you are saying 0 or more times.That why you are getting the last digit which in this case 6.


Thanks

Anil Kumar
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look in our SCJP FAQ, or search the forum for this often asked question.
[ May 24, 2007: Message edited by: Barry Gaunt ]
 
Hardik Raja
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Barry,

Got the answer..Thank you

Regards,
Hardik.S.Raja
[ May 25, 2007: Message edited by: Hardik Raja ]
 
Mercurio Savedra
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why this code doesnt fail, shouldnt be the regex expresion something like "\\d*" instead "\d*" in order to inform the compiler that this is not an escape character
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic