I have the following code. As far as I can see, the program should print 0123445. Instead, it prints 01234456.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex2 {
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d*");
Matcher m = p.matcher("ab34ef");
boolean b = false;
while(b=m.find()){
System.out.print(m.start() + m.group());
}
System.out.println();
}
}
I think the following should happen- Since the search pattern is for a \d*,
- It finds a hit at position 0, but since the hit is not a digit, it just prints 0
- It finds a hit at position 1, but again, not a digit, prints 0
- Finds a hit at position 2 and since we are looking for \d*, the hit is 34, and so it prints 234.
- Moves to position 4, finds a hit, but since hit is not a digit, it just prints 4.
- Moves to position 5, finds a hit, but since hit is not a digit, it just prints 5.
At this point, as far as I can see, it should be done. But for some reason, the program also returns a 6.
Much appreciate it if someone can explain.