• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Regex doubt

 
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is about a question from scjp 6 book by Kathy and Bert.

Question:
Pattern p = Pattern.compile("\\d*")
Matcher m = p.matcher("ab34ef");

For this, while I try to print the return value of m.start(), I get the following output:
012456

Though there is only 6 characters in the matcher string, how is 6 getting printed along the output and why is 3 being left out.
My guess, though wrong was
01245


Regards
Larsen
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Larsen.

The '6' is the result of the regex finding a zero match after the last character.

Try using "ab" as the matcher String, and you;ll get the output "012" - one zero match before the first character, one between each character, and one after the last character.

'3' is not output because that's the index between the '3' and the '4' digits - the regex is treating the '34' as a match and consumes both digits.

Try printing out the matched group, with brackets around it so you can see the empty matches, and enter various values for the match:



(It took me a while to understand this strange regex behaviour )
 
Larsen Raja
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for a quick response.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic