【正则表达式】之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
總結
以上是生活随笔為你收集整理的【正则表达式】之Possessive Quantifiers的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cogs 2320. [HZOI 201
- 下一篇: Jinja2初探