Regex知識詳解之貪婪模式和非貪婪模式 (java版樣本)__Regex

來源:互聯網
上載者:User

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]












聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.