Why do I get the output ab for the following regular-expression code with a Relucutant quantifier?
Pattern p = Pattern.compile("abc*?");
Matcher m = p.matcher("abcfoo");
while(m.find())
System.out.println(m.group()); // ab
Similarly, why do I get empty indices for the following code?
Pattern p = Pattern.compile(".*?");
Matcher m = p.matcher("abcfoo");
while(m.find())
System.out.println(m.group());
In addition to Konrad Rudolph’s answer:
matches
"ab"in any case and"c"only if it must. Since nothing follows the*?, the regex engine stops immediately. If you had:then it would match
"abcf"be cause the"c"must match in order to allow the"f"to match, too. The other expression:matches nothing because this pattern is 100% optional.
would match
"abcf"again.