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.
Code
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
Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.