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()); } }
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()); } }
查找字串:xfooxxxxxxfoo
結果:
//未匹配成功
其比較過程如下
/tutorial/essential/regex/quant.html
再來看看幾個例子:
模式串:.+[0-9]
查找串:abcd5aabb6
模式串:.+?[0-9]查找串:abcd5aabb6結果:matched form 0 to 4 模式串:.{1,9}+[0-9]查找串:abcd5aabb6
結果:matched form 0 to 10
模式串:.{1,10}+[0-9]
查找結果:abbb