# 【正则表达式】之Possessive Quantifiers

## Greediness（贪婪型）

``````Pattern p = Pattern.compile("\\[.+\\]\\[.+\\]");
Matcher m = p.matcher("[che][1]'s blog is [rebey.cn][2],and built in [2016][3].");
while(m.find()) {
System.out.println(m.group());
}

// 结果：[che][1]'s blog is [rebey.cn][2],and built in [2016][3]``````

“\[.+”先遍历到字符“.”时发现不匹配了，开始往左回溯，得到“[che...]”;

## Reluctant/Laziness（勉强型）

``````Pattern p1 = Pattern.compile("\\[.+?\\]\\[.+?\\]");
Matcher m1 = p1.matcher("[che][1]'s blog is [rebey.cn][2],and built in [2016][3].");
while(m1.find()) {
System.out.println(m1.group());
}

// 结果：
//    [che][1]
//    [rebey.cn][2]
//    [2016][3]``````

## Possessive（占有型）

``````Pattern p2 = Pattern.compile("\\[.++\\]\\[.++\\]");
Matcher m2 = p2.matcher("[che][1]'s blog is [rebey.cn][2],and built in [2016][3].");
while(m2.find()) {
System.out.println(m2.group());
}

// 结果：匹配不到``````

“\[.+”匹配“[che...”直到最后字符“.”不匹配，立即结束。

## x+ ≈ (?>x)

``````Pattern p3 = Pattern.compile("\\[.++");
Matcher m3 = p3.matcher("[che][1]'s blog is [rebey.cn][2],and built in [2016][3].");
while(m3.find()) {
System.out.println(m3.group());
}

Pattern p4 = Pattern.compile("(?>(\\[.+))");
Matcher m4 = p4.matcher("[che][1]'s blog is [rebey.cn][2],and built in [2016][3].");
while(m4.find()) {
System.out.println(m4.group());
}

## 说点什么

Possessive quantifiers are a way to prevent the regex engine from trying all permutations.

With a possessive quantifier, the deal is all or nothing.

The main practical benefit of possessive quantifiers is to speed up your regular expression.

## 参考文献

Regex Tutorial - Possessive Quantifiers

190 声望
34 粉丝