Doug
Doug

Reputation: 19

Java: pattern matcher method returns wrong result

I have tried really hard to understand this, but I just don't get it. I don't understand why the start() method returns "456" after the group() method returns "34".

Pattern p = Pattern.compile("\\d*");
Matcher m = p.matcher("ab34ef");
while(m.find())
{
    System.out.print(m.start()+m.group());  // output: 01234456
}

Upvotes: 0

Views: 266

Answers (1)

jrtapsell
jrtapsell

Reputation: 7001

Regex explained

Your regex finds 0 length items,which adds a lot of matches of 0 length.

Explained

As the output is all on 1 line I split it to make it more readable.

Pattern p = Pattern.compile("\\d*");
Matcher m = p.matcher("ab34ef");
while(m.find()) {
    System.out.printf("start:%s end:%s text:'%s'%n", m.start(), m.end(), m.group());
}

Output:

start:0 end:0 text:''
start:1 end:1 text:''
start:2 end:4 text:'34'
start:4 end:4 text:''
start:5 end:5 text:''
start:6 end:6 text:''

This matches your output of 01234456:

  • 0, 1 and 2 are all group starts
  • 34 is the match text
  • 4, 5 and 6 are all group starts

Upvotes: 1

Related Questions