Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression "\\d?" giving incorrect output [duplicate]

Tags:

java

regex

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.

like image 748
user1655165 Avatar asked Mar 07 '26 16:03

user1655165


2 Answers

\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.

like image 194
Marko Topolnik Avatar answered Mar 10 '26 06:03

Marko Topolnik


\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+");
like image 20
Bohemian Avatar answered Mar 10 '26 07:03

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!