javaRegex學習筆記(三)

來源:互聯網
上載者:User

在(一)和(二)中只是瞭解了一下Regex,今天深入了學習Regex在string類的應用,主要在matches(),split(),replace(),replaceAll(),replaceFirst等方法的應用.

現在先看看它們在JDK1.6中的定義:
matches
  public boolean matches(String regex)

  告知此字串是否匹配給定的Regex。 

replace
  public String replace(char oldChar,char newChar)

  返回一個新的字串,它是通過用 newChar 替換此字串中出

split
  public String[] split(String regex,int limit)

  根據匹配給定的Regex來拆分此字串。
  public String[] split(String regex)

  根據給定Regex的匹配拆分此字串.該方法的作用就像是使用給定的運算式和限制參數 0 來調用兩參數 split 方法。因此,所得數組中不包括結尾Null 字元串。

replaceAll
  public String replaceAll(String regex,String replacement)

  使用給定的 replacement 替換此字串所有匹配給定的Regex的子字串。
replaceFirst
  public String replaceFirst(String regex,String replacement)

  使用給定的 replacement 替換此字串匹配給定的Regex的第一個子字串。

關於以上方法的詳細資料可以到JDK中查閱,在這裡就不多說了,下面用一個例子來說明以上這些方法怎麼樣用的.

public class TestRegex{
public static void main(String[] args){
String str = "lovefeel2004@126.com";
//matches()的用法
String regex1 = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+[.]((net)|(com)|(com.cn))$";
boolean b ;
b = str.matches(regex1);
p(b+"\n");

//spilt()的用法
String[] split1 = str.split("@");
p("用@去分割str得到的字串:");
for(String s : split1){
p(s+" ");
}

String[] split2 = str.split("@|\\.");
p("\n用@或.去分割str得到的字串:");
for(String s : split2){
p(s+" ");
}
//replace(),replaceAll(),replaceFirst()的用法
p("\n用#去代替@後的str:");
p(str.replace("@","#") + "\n");
p("用d去代替o後的str:");
p(str.replaceAll("o","d") + "\n");
p("用d代替第一個o後的str:");
p(str.replaceFirst("o","d") + "\n");

}
//列印方法
public static void p(Object o){
System.out.print(o);
}
}

結果:

接下來再學習java.util.regex包的類,畢竟String只提供簡單的Regex功能.

 

本文如有不正確,請大家指正!!!

聯繫我們

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