javaregexreluctant-quantifiers

Reason for the behavior of the reluctunt quantifier ?? in java regex


I know that the ? is a greedy quantifier and ?? is the reluctant one for it. When I use it as follows it gives me an empty output always? Is it because of it always operates from left to right (first looking at the zero occurrence then the matched occurrence) or another one?

    Pattern pattern = Pattern.compile("a??");
    Matcher matcher = pattern.matcher("aba");
    while(matcher.find()){
        System.out.println(matcher.start()+"["+matcher.group()+"]"+matcher.end());
    }

Output :

0[]0
1[]1
2[]2
3[]3

Solution

  • Your regex could be explained as follows: "try to match zero characters, and if that fails try to match one 'a' character".

    Trying to match zero characters will always succeed, so there is really no purpose for a regex that only contains a single reluctant element.