Zero-length matches in Java Regex

patrician

New Member
My code : \[code\]Pattern pattern = Pattern.compile("a?");Matcher matcher = pattern.matcher("ababa");while(matcher.find()){ System.out.println(matcher.start()+"["+matcher.group()+"]"+matcher.end());}\[/code\]Output : \[code\]0[a]11[]12[a]33[]34[a]55[]5\[/code\]What I know :
  • "a?" stands for zero or one occurrence of the character 'a'.
Java API says :
  • matcher.start() returns the start index of the previous match.
  • matcher.end() returns the offset after the last character matched.
  • matcher.group() returns the input subsequence matched by the previousmatch. For a matcher m with input sequence s, the expressionsm.group() and s.substring(m.start(), m.end()) are equivalent. And forsome patterns, for example a*, match the empty string. This methodwill return the empty string when the pattern successfully matchesthe empty string in the input.
What I want to know:[*]In which situations does the regex engine encounters a zerooccurrence of a given character(s) - Here for character 'a'.[*]In those situation what are values actually returns by the start(),end() and group() methods in the matcher. I have mentioned what thejava API said. But I'm little unclear when it comes to the practicalsituation as above.
 
Top