0

I am Relatively inexperienced in regex. I am playing around with various java classes that are used for regex. Below is an example I am trying out -

import java.util.regex.*;

public class Regex {
    public static void main(String[] args){
        Pattern p = Pattern.compile("\\d*");
        Matcher m = p.matcher("ab34ef");
        while(m.find()){
            System.out.println(m.start() + m.group());
        }
    }   
}

When I run this I get -

0
1
234
4
5
6

The m.start() function returns the position of the character the match was found on. The pattern follows a 0 based index.

So here is my interpretation of the output -

0   (index = 0 , no matching group)
1   (index = 1 , no matching group)
234 (index = 2 , matching group = 34)
4   (index = 4 , no matching group)
5   (index = 5 , no matching group)
6   (Why does this happen?)

Why would m.start() return 6 ? The string is 6 characters long so the last index should be 5. I think I am missing something very basic here. Any pointers or suggestions are welcome.

Nilay Sundarkar
  • 381
  • 4
  • 15

0 Answers0