Posted on 2008-10-04 19:50
Qzi 閱讀(1049)
評論(0) 編輯 收藏 所屬分類:
java foundation
Pattern類:
例子:
Pattern pattern = Pattern.compile("[,\\s]+");
String[] result = pattern.split("one two three,four,five, six");
for(int i = 0; i<result.length; i++){
System.out.println(result[i]);
}
輸出結果是:
one
two
three
four
five
six
Pattern類的靜態方法compile用來編譯正則表達式,在此[,\\s]+表示若干個","或者若干個空格匹配
split方法使用正則匹配將字符串切割成各子串并且返回
Matcher類:
注意,Matcher的獲得是通過Pattern.matcher(CharSequence charSequence);輸入必須是實現了CharSequence接口的類
常用方法:
matches()判斷整個輸入串是否匹配,整個匹配則返回true
例如下面會輸出true
String str1 = "hello";
Pattern pattern1 = Pattern.compile("hello");
Matcher matcher1 = pattern1.matcher(str1);
System.out.println(matcher1.matches());
lookingAt()從頭開始尋找,找到匹配則返回true
例如下面會輸出true
String str2 = "hello yangfan!";
Pattern pattern2 = Pattern.compile("hello");
Matcher matcher2 = pattern2.matcher(str2);
System.out.println(matcher2.lookingAt());
find()掃描輸入串,尋找下一個匹配子串,存在則返回true
例如下面將會將所有no替換成yes
Pattern pattern = Pattern.compile("no");
Matcher matcher = pattern.matcher("Does jianyue love yangfan? no;" +
"Does jianyue love yangfan? no;Does jianyue love yangfan? no;");
StringBuffer sb = new StringBuffer();
boolean find = matcher.find();
while(find){
matcher.appendReplacement(sb, "yes");
find = matcher.find();
}
matcher.appendTail(sb);
System.out.println(sb.toString());