【正则表达式】之Possessive Quantifiers

针对“*”、“+”、“?”等限定符都是贪婪的(尽可能多的匹配字符),通过在最后追加“+”或“?”量词可改变贪婪性。本篇主要解疑正则表达式的“占有型量词”(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...]”;
继续往左回溯,像这样“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());
}

结果皆为:[che][1]'s blog is [rebey.cn][2],and built in [2016][3].

注意括号。

说点什么

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.

占有量词的主要实际意义是加速你的正则表达式。

更多有意思的内容,欢迎访问笔者小站: rebey.cn

参考文献

Regex Tutorial - Possessive Quantifiers

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...