Java正則表達中Greedy Reluctant Possessive 的區別,greedypossessive
上一篇文章《編程思想之Regex 》中講了Regex的原理、使用方法和常見的Regex總結,本文將進一步探討Java正則表達中Greedy、Reluctant、Possessive三種策略的區別。
從Java的官方文檔http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html中我們可以看到,Regex表示數量詞的符號有三套,分別是Greedy(貪婪的)、Reluctant(勉強的)和Possessive(獨佔的)。其含意如下:
|
Greedy 數量詞 |
|
X? |
X,一次或一次也沒有 |
|
X* |
X,零次或多次 |
|
X+ |
X,一次或多次 |
|
X{n} |
X,恰好 n 次 |
|
X{n,} |
X,至少 n 次 |
|
X{n,m} |
X,至少 n 次,但是不超過 m 次 |
|
|
|
|
Reluctant 數量詞 |
|
X?? |
X,一次或一次也沒有 |
|
X*? |
X,零次或多次 |
|
X+? |
X,一次或多次 |
|
X{n}? |
X,恰好 n 次 |
|
X{n,}? |
X,至少 n 次 |
|
X{n,m}? |
X,至少 n 次,但是不超過 m 次 |
|
|
|
|
Possessive 數量詞 |
|
X?+ |
X,一次或一次也沒有 |
|
X*+ |
X,零次或多次 |
|
X++ |
X,一次或多次 |
|
X{n}+ |
X,恰好 n 次 |
|
X{n,}+ |
X,至少 n 次 |
|
X{n,m}+ |
X,至少 n 次,但是不超過 m 次 |
Greedy、Reluctant、Possessive的區別執行個體說話
看上面的表格我們發現這三種數量詞的含意都相同(如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());
}
} |
結果:
matched form 0 to 4
matched form 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
結果:matched form 0 to 13
其比較過程如下
Reluctant採用與Greedy相反的方法,它從輸入串的首(字元)位置開始,在一次嘗試匹配尋找中只勉強地讀一個字元,直到嘗試完整個字串。
模式串:.*foo
尋找串:xfooxxxxxxfoo
結果:matched form 0 to 4
matched form 4 to 13
其比較過程如下
Possessive數量詞總是讀入整個輸入串,嘗試一次(僅且一次)匹配成功,不像Greedy,Possessive從不回退,即便這樣做也可能使整體匹配成功。
模式串:.*foo
尋找串:xfooxxxxxxfoo
結果:
//未匹配成功
其比較過程如下
參考文章:http://docs.oracle.com/javase/tutorial/essential/regex/quant.html
再來看看幾個例子:
模式串:.+[0-9]
尋找串:abcd5aabb6
結果:matched form 0 to 10
模式串:.+?[0-9]
尋找串:abcd5aabb6
結果:matched form 0 to 4
模式串:.{1,9}+[0-9]
尋找串:abcd5aabb6
結果:matched form 0 to 10
模式串:.{1,10}+[0-9]
尋找串:abcd5aabb6
結果:匹配失敗
如果您有什麼疑惑和想法,請在評論處給予反饋,您的反饋就是最好的測評師!由於本人技術和能力有限,如果本博文有錯誤或不足之處,敬請諒解並給出您寶貴的建議!
========================歡迎關注編程思想系列文章========================
編程思想之Regex
編程思想之迭代器
編程思想之遞迴
編程思想之回調