日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

【正则表达式】之Possessive Quantifiers

發(fā)布時(shí)間:2025/3/21 编程问答 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【正则表达式】之Possessive Quantifiers 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

針對(duì)“*”、“+”、“?”等限定符都是貪婪的(盡可能多的匹配字符),通過(guò)在最后追加“+”或“?”量詞可改變貪婪性。本篇主要解疑正則表達(dá)式的“占有型量詞”(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()); }// 結(jié)果:[che][1]'s blog is [rebey.cn][2],and built in [2016][3]

在不做任何額外處理情況下,正則表達(dá)式默認(rèn)是貪婪型的。貪婪型一次讀取所有字符進(jìn)行匹配。
以下是匹配過(guò)程猜想:
“\[.+”先遍歷到字符“.”時(shí)發(fā)現(xiàn)不匹配了,開(kāi)始往左回溯,得到“[che...]”;
繼續(xù)往左回溯,像這樣“che...”,因此就有了以上的輸出結(jié)果。

Reluctant/Laziness(勉強(qiáng)型)

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()); }// 結(jié)果: // [che][1] // [rebey.cn][2] // [2016][3]

在原有的“.+”之后加個(gè)“?”,就成為了勉強(qiáng)型。它將從左至右依次讀取進(jìn)行匹配,直到字符串結(jié)束。

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()); }// 結(jié)果:匹配不到

在原有的“.+”之后加個(gè)“+”,就成為了占有型。它也是一次讀取所有字符串進(jìn)行匹配,區(qū)別在于它不回溯。
以下是匹配過(guò)程猜想:
“\[.+”匹配“[che...”直到最后字符“.”不匹配,立即結(jié)束。

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()); }結(jié)果皆為:[che][1]'s blog is [rebey.cn][2],and built in [2016][3].

注意括號(hào)。

說(shuō)點(diǎn)什么

Possessive quantifiers are a way to prevent the regex engine from trying all permutations.

占有量詞是一種用來(lái)組織正則表達(dá)式嘗試所有排列組合的方式。(即不回溯)

With a possessive quantifier, the deal is all or nothing.

使用占有量詞只有兩種結(jié)果,全匹配或者空匹配。

The main practical benefit of possessive quantifiers is to speed up your regular expression.

占有量詞的主要實(shí)際意義是加速你的正則表達(dá)式。

更多有意思的內(nèi)容,歡迎訪問(wèn)筆者小站: rebey.cn

參考文獻(xiàn)

Regex Tutorial - Possessive Quantifiers

總結(jié)

以上是生活随笔為你收集整理的【正则表达式】之Possessive Quantifiers的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。