Java Pattern Mattcher

I have
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class TestPrim {
      public static void main(String args[]){
            

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

      }
}


the output is : 012333566689
however I cant understand how I got 9 whilst the highest index is 8 in my string, any clarification ?
TheSilverBulletAsked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
>>however I cant understand how I got 9 whilst the highest index is 8 in my string, any clarification ?

Because you've asked it to match a digit or no digit. Just ask it to match a digit

Pattern p = Pattern.compile("\\d");
0
 
Bart CremersJava ArchitectCommented:
Matches:

At index 0 -> empty string
At index 1 -> empty string
At index 2 -> 333
At index 5 -> empty string
At index 6 -> 66
At index 8 -> empty string
At index 9 -> empty string

If you want to match a single digit, do as CEHJ says and drop the *.
If you want to match at least one digit, use "\\d+"
0
 
objectsCommented:
because it is matching the empty string at the *end of the line*
0
 
CEHJCommented:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.