【正则表达式】之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] 在不做任何额外处理情况下,正则表达式默认是贪婪型的。贪婪型一次读取所有字符进行匹配。 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()); } // 结果:匹配不到 在原有的“.+”之后加个“+”,就成为了占有型。它也是一次读取所有字符串进行匹配,区别在于它不回溯。 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]. 注意括号。 说点什么
占有量词是一种用来组织正则表达式尝试所有排列组合的方式。(即不回溯)
使用占有量词只有两种结果,全匹配或者空匹配。
占有量词的主要实际意义是加速你的正则表达式。 更多有意思的内容,欢迎访问笔者小站: rebey.cn 参考文献Regex Tutorial - Possessive Quantifiers (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |