public void name() throws Exception {
Pattern p = Pattern.compile("\\d{1,2}?");
String input = "09";
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer();
while(m.find()) {
System.out.println("match = "+m.group());
}
}
Output of the above method is :
match = 0
match = 9
Now, I am just adding parenthesis to the regexp:
public void name() throws Exception {
Pattern p = Pattern.compile("(\\d{1,2})?");
String input = "09";
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer();
while(m.find()) {
System.out.println("match = "+m.group());
}
}
And the output becomes:
match = 09
match =
- Why do parenthesis make the matching greedy here?
- [Edit,added later]Why is empty string not matched in the first case?