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

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

高洛峰
高洛峰原創
2016-10-15 13:36:432041瀏覽

從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