Regex知識詳解系列,通過程式碼範例來說明Regex知識,建議自己按照例子手打一遍。
本樣本的原始碼下載地址:http://download.csdn.net/detail/gnail_oug/9504094
樣本:
1、貪婪模式提取html標籤裡的內容
2、非貪婪模式提前html標籤裡的內容
//提取td元素裡的內容String str="<table><tr><td>hello world</td><td>hello regex</td></tr></table>";//貪婪模式 * + {n,} 預設情況是貪婪模式比對System.out.println("====貪婪模式=====");//編譯Regex到模式對象Pattern p=Pattern.compile("<td>.*</td>");//得到匹配器Matcher m=p.matcher(str);//通過find方法尋找匹配,找到就返回true,否則返回falsewhile(m.find()){//通過group方法擷取前面find尋找到的子字串,start、end方法擷取子字串開始和結束位置System.out.println(m.group()+" 位置:["+m.start()+","+m.end()+"]");}//非貪婪模式,?跟在 * + {n,} 等的後面時,表示非貪婪模式,注意和子運算式後面的?區分開,子運算式後的?表示匹配0次或1次System.out.println("====非貪婪模式=====");p=Pattern.compile("<td>.*?</td>");m=p.matcher(str);while(m.find()){System.out.println(m.group()+" 位置:["+m.start()+","+m.end()+"]");}
運行結果:
====貪婪模式=====<td>hello world</td><td>hello regex</td> 位置:[11,51]====非貪婪模式=====<td>hello world</td> 位置:[11,31]<td>hello regex</td> 位置:[31,51]