在(一)和(二)中只是瞭解了一下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功能.
本文如有不正確,請大家指正!!!