java中Regex的一般用法

來源:互聯網
上載者:User

java中提供Regex功能的類在java.util.regex包下,有兩個類:Pattern 和 Matcher。正則表達會先被編譯為Pattern類,然後建立匹配器,由匹配器進行匹配,典型的調用順序為:

 

 Pattern p = Pattern.compile("a*b");
 Matcher m = p.matcher("aaaaab");
 boolean b = m.matches();

 

也可以調用 

      while(m.find())

       {

              System.out.println(m.group());

        }

如果有擷取的群組可以用m.group(i)來提取相應的擷取的群組,其中i為擷取的群組的序號,0表示整體。

 

我們可以看到其實用法是很簡單,最重要的步驟還在於寫出正確的Regex,下面是幾種常用的運算式:

 

這些運算式有很多是javascript的,很多語言中都有Regex的實現,寫法也略有不同,不過如果理解了的話,表面上的不同也不會有什麼障礙,我們可以根據它來寫滿足我們自己需要的運算式。

 

匹配中文字元的Regex: [\u4e00-\u9fa5]

匹配雙位元組字元(包括漢字在內):[^\x00-\xff]

 

匹配空行的Regex:\n[\s| ]*\r

匹配HTML標記的Regex:/<(.*)>.*<\/\1>|<(.*) \/>/

匹配首尾空格的Regex:(^\s*)|(\s*$)

 

匹配Email地址的Regex:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

匹配網址URL的Regex:http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

 

 

只能輸入數字和英文的:
<input onkeyup="value=value.replace(/[\W]/g,'') " onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))" ID="Text1" NAME="Text1">

只能輸入數位:
<input onkeyup="value=value.replace(/[^\d]/g,'') " onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))" ID="Text2" NAME="Text2">

只能輸入全形的:
<input onkeyup="value=value.replace(/[^\uFF00-\uFFFF]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\uFF00-\uFFFF]/g,''))" ID="Text3" NAME="Text3">

只能輸入漢字的:
<input onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))" ID="Text4" NAME="Text4">

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.