接著學習java.util.regex包裡關於Regex的包,因為string類只提供部分Regex的功能,不能充
分展現Regex強大的功能.
java.util.regex包裡有兩個類,一個介面,一個異常,Regex的主要功能都是在Pattern,Matcher兩個
類裡實現了,現在先學習Pattern類,Pattern類一共有8個方法和兩個方法的重載,還有8個欄位,下面直接看
一個例子你就明白他的原理,如果不明白可以查看JDK的協助.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
//compile(),split(),flags(),matcher(),matches(),quote(),toString(),pattern()
class PatternTest{
public static void main(String[] args){
String regex = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+[.]((net)|(com)|(com.cn)|(cn))$";
Pattern p = Pattern.compile(regex);
String result = p.pattern();
p(result);
p(p.flags());
result = p.toString();
p(result);
String regex1 = "mx";
Pattern p1 = Pattern.compile(regex1);
Matcher m1 = p1.matcher("abcdefgABCDEFG");
while(m1.find()){
p(m1.group());//abc
}
Pattern p2 = Pattern.compile(regex1,Pattern.CASE_INSENSITIVE);
Matcher m2 = p2.matcher("abcdefgABCDEFG");
while(m2.find()){
p(m2.group());//abc ABC
}
p(p2.flags());
boolean b ;
b = Pattern.matches(regex,"lovefeel2004@126.com");
p(b);
p(Pattern.quote("lovefeel2004@126.com"));
Pattern p3 = Pattern.compile("@");
String[] result1 = p3.split("love@feel@2004@com@cn");
for(String s: result1){
p(s);
}
result1 = p3.split("love@feel@2004@com@cn",3);
for(String s: result1){
p(s);
}
}
public static void p(Object o){
System.out.println(o);
}
}
運行結果: