← 中文资源

简体中文版本

贪婪、勉强与占有量词

贪婪量词吃到最远再回退、勉强量词在第一个边界就停、占有量词绝不交还字符——同一份输入三种量词给出不同的捕获范围,占有形态还天然免疫灾难性回溯。

阅读英文原文

实现说明

除了类 QuantifierModes和函数 main,文件里再无其他定义。 这个示例中仅有的重复出现在 while (reluctant.find()) 里。

使用要点

  • 每一步打印都带着自己的标签:greedy:、reluctant:、possessive found:。

常见问题

运行「贪婪、勉强与占有量词」会打印什么?

运行文件本身,greedy:、reluctant:、possessive found: 这些前缀各对应一段演示逻辑。

核心语句

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

代码示例

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());
    }
}