【正则表达式】之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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值