【正则表达式】之Possessive Quantifiers

前端之家收集整理的这篇文章主要介绍了【正则表达式】之Possessive Quantifiers前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

针对“*”、“+”、“?”等限定符都是贪婪的(尽可能多的匹配字符),通过在最后追加“+”或“?”量词可改变贪婪性。本篇主要解疑正则表达式的“占有型量词”(Possessive Quantifiers)。

Greediness(贪婪型)

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

在不做任何额外处理情况下,正则表达式默认是贪婪型的。贪婪型一次读取所有字符进行匹配。
以下是匹配过程猜想:
“\[.+”先遍历到字符“.”时发现不匹配了,开始往左回溯,得到“[che...]”;
继续往左回溯,像这样“che...”,因此就有了以上的输出结果。

Reluctant/Laziness(勉强型)

  1. Pattern p1 = Pattern.compile("\\[.+?\\]\\[.+?\\]");
  2. Matcher m1 = p1.matcher("[che][1]'s blog is [rebey.cn][2],and built in [2016][3].");
  3. while(m1.find()) {
  4. System.out.println(m1.group());
  5. }
  6.  
  7. // 结果:
  8. // [che][1]
  9. // [rebey.cn][2]
  10. // [2016][3]

在原有的“.+”之后加个“?”,就成为了勉强型。它将从左至右依次读取进行匹配,直到字符串结束。

Possessive(占有型)

  1. Pattern p2 = Pattern.compile("\\[.++\\]\\[.++\\]");
  2. Matcher m2 = p2.matcher("[che][1]'s blog is [rebey.cn][2],and built in [2016][3].");
  3. while(m2.find()) {
  4. System.out.println(m2.group());
  5. }
  6.  
  7. // 结果:匹配不到

在原有的“.+”之后加个“+”,就成为了占有型。它也是一次读取所有字符串进行匹配,区别在于它不回溯。
以下是匹配过程猜想:
“\[.+”匹配“[che...”直到最后字符“.”不匹配,立即结束。

x+ ≈ (?>x)

  1. Pattern p3 = Pattern.compile("\\[.++");
  2. Matcher m3 = p3.matcher("[che][1]'s blog is [rebey.cn][2],and built in [2016][3].");
  3. while(m3.find()) {
  4. System.out.println(m3.group());
  5. }
  6.  
  7. Pattern p4 = Pattern.compile("(?>(\\[.+))");
  8. Matcher m4 = p4.matcher("[che][1]'s blog is [rebey.cn][2],and built in [2016][3].");
  9. while(m4.find()) {
  10. System.out.println(m4.group());
  11. }
  12.  
  13. 结果皆为:[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

猜你在找的正则表达式相关文章