首頁 类库下载 java类库 Java正規表達中Greedy Reluctant Possessive 的差異

Java正規表達中Greedy Reluctant Possessive 的差異

Oct 15, 2016 pm 01:36 PM

從Java的官方文件http://docs.Oracle.com/javase/7/docs/api/java/util/regex/Pattern.html中我們可以看到,正規表示數量詞的符號有三套,分別是Greedy(貪婪的)、Reluctant(勉強的)和Possessive(獨佔的)。其含意如下:

Java正規表達中Greedy Reluctant Possessive 的差異

Greedy、Reluctant、Possessive的區別

實例說話

看上面的表格我們發現這三種數量詞的含意都相同(如X?、X??、X+、X??、X+、X?表示一次或一次也沒有),但他們之間還是有一些細微的差別的。我們先來看一個例子:

1.Greedy

public static void testGreedy() {  
    Pattern p = Pattern.compile(".*foo");  
    String strText = "xfooxxxxxxfoo";  
    Matcher m = p.matcher(strText);  
    while (m.find()) {  
        System.out.println("matched form " + m.start() + " to " + m.end());  
    }  
}
登入後複製

結果:

matched form 0 to 13

2.Reluctant

public static void testReluctant() {  
    Pattern p = Pattern.compile(".*?foo");  
    String strText = "xfooxxxxxxfoo";  
    Matcher m = p.matcher(strText);  
    while (m.find()) {  
        System.out.println("matched form " + m.start() + " to " + m.end());  
    }  
}
登入後複製
4 to 13

3.Possessive

public static void testPossessive() {  
    Pattern p = Pattern.compile(".*+foo");  
    String strText = "xfooxxxxxxfoo";  
    Matcher m = p.matcher(strText);  
    while (m.find()) {  
        System.out.println("matched form " + m.start() + " to " + m.end());  
    }  
}
登入後複製
結果:

//未匹配成功

原理講解

Greedy數量詞被稱為「貪婪的」是因為匹配器被強制要求第一次嘗試匹配時讀入整個輸入串,如果如果第一次嘗試匹配失敗,則從後往前逐個字元地回退並嘗試再次匹配,直到匹配成功或沒有字元可回退。

模式串:.*foo

查找串:xfooxxxxxxfoo

結果:.*foo

查找串:xfooxxxxxxfoo

結果:matched form 0 to 13

其比較過程與首

Java正規表達中Greedy Reluctant Possessive 的差異

? )位置開始,在一次嘗試匹配查找中只勉強地讀一個字符,直到嘗試完整個字符串。

模式串:.*foo

查找串:xfooxxxxxxfoo

結果:matched form 0 to 4

matched form 4comto 13 4

matched form 4) 的兩種比較入整個輸入字串,嘗試一次(僅且一次)匹配成功,不像Greedy,Possessive從不回退,即使這樣做也可能使整體匹配成功。

模式字串:.*foo

Java正規表達中Greedy Reluctant Possessive 的差異查找字串:xfooxxxxxxfoo

結果:

//未匹配成功

其比較過程如下

/tutorial/essential/regex/quant.html

再來看看幾個例子:

模式串:.+[0-9]

查找串:abcd5aabb6Java正規表達中Greedy Reluctant Possessive 的差異

 模式串:.+?[0-9]

查找串:abcd5aabb6

結果:matched form 0 to 4

 

模式串:.{1,9}+[0-9]

查找串:abcd5aabb6

結果:matched form 0 to 10

 

模式串:.{1,10}+[0-9]

查找結果:abbb

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)