Greedy Reluctant Possessive Quantifiers

Greedy patterns grab to the last delimiter, reluctant ones stop at the first, and possessive ones never give back, so catastrophic backtracking cannot happen.

JavaCli Tooling

Code

snippet
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class QuantifierModes {

    public static void main(String[] args) {
        String input = "<b>first</b> and <b>second</b>";

        // 贪心(greedy):.* 先吃到行尾,再逐字符回吐让 </b> 成立
        // → 一口吞下跨标签的整段
        Matcher greedy = Pattern.compile("<b>(.*)</b>").matcher(input);
        if (greedy.find()) {
            System.out.println("greedy:    " + greedy.group(1));
        }

        // 勉强(reluctant):.*? 在第一个 </b> 前就满足 → 逐段匹配
        Matcher reluctant = Pattern.compile("<b>(.*?)</b>").matcher(input);
        while (reluctant.find()) {
            System.out.println("reluctant: " + reluctant.group(1));
        }

        // 占有(possessive):.*+ 绝不交还吃到的字符,
        // 后面的 </b> 无处安放 → 匹配失败,也因此天然免疫灾难性回溯
        Matcher possessive = Pattern.compile("<b>.*+</b>").matcher(input);
        System.out.println("possessive found: " + possessive.find());
    }
}

Inside the snippet

Count the class QuantifierModes and the function main as the entire surface area of Greedy Reluctant Possessive Quantifiers.

while (reluctant.find()) is the loop that carries the per-item work.

Using it

Output lines are prefixed (greedy:, reluctant:, possessive found:), making each step’s effect easy to spot.

Key statements

Matcher reluctant = Pattern.compile("<b>(.*?)</b>").matcher(input);
Matcher possessive = Pattern.compile("<b>.*+</b>").matcher(input);
Matcher greedy = Pattern.compile("<b>(.*)</b>").matcher(input);

Interactive Tools for This Topic

FAQ

What does Greedy Reluctant Possessive Quantifiers print when run?
Execute the whole file; each printed line is prefixed with a label like `greedy:`, `reluctant:`, `possessive found:`.