3

Sample code

Pattern p = Pattern.compile("\\d?");
Matcher m = p.matcher("ab34ef");
boolean b = false;
while (m.find())
{
    System.out.print(m.start());// + m.group());
}

Answer: 012456

But string total length is 6. So How m.start will give 6 in the output, as index starts
from 0.

rptmat57
  • 3,643
  • 1
  • 27
  • 38

2 Answers2

3

\d? matches zero or one character, so it starts beyond the last character of the string as well, as a zero-width match.

Note that your output is not in fact attained by \d?, but by \d*. You should change either one or the other to make the question self-consistent.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1

\d? matches zero or one digit, which matches every digit, but also matches every character boundary.

Try matching at least one digit:

Pattern p = Pattern.compile("\\d+");
Bohemian
  • 412,405
  • 93
  • 575
  • 722