java 正則表達(dá)式pattern類Matcher類
Posted on 2008-10-04 19:50 Qzi 閱讀(1054) 評(píng)論(0) 編輯 收藏 所屬分類: java foundationPattern類:
例子:
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]);
}
輸出結(jié)果是:
one
two
three
four
five
six
Pattern類的靜態(tài)方法compile用來(lái)編譯正則表達(dá)式,在此[,\\s]+表示若干個(gè)","或者若干個(gè)空格匹配
split方法使用正則匹配將字符串切割成各子串并且返回
Matcher類:
注意,Matcher的獲得是通過(guò)Pattern.matcher(CharSequence charSequence);輸入必須是實(shí)現(xiàn)了CharSequence接口的類
常用方法:
matches()判斷整個(gè)輸入串是否匹配,整個(gè)匹配則返回true
例如下面會(huì)輸出true
String str1 = "hello";
Pattern pattern1 = Pattern.compile("hello");
Matcher matcher1 = pattern1.matcher(str1);
System.out.println(matcher1.matches());
lookingAt()從頭開(kāi)始尋找,找到匹配則返回true
例如下面會(huì)輸出true
String str2 = "hello yangfan!";
Pattern pattern2 = Pattern.compile("hello");
Matcher matcher2 = pattern2.matcher(str2);
System.out.println(matcher2.lookingAt());
find()掃描輸入串,尋找下一個(gè)匹配子串,存在則返回true
例如下面將會(huì)將所有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());
例子:
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]);
}
輸出結(jié)果是:
one
two
three
four
five
six
Pattern類的靜態(tài)方法compile用來(lái)編譯正則表達(dá)式,在此[,\\s]+表示若干個(gè)","或者若干個(gè)空格匹配
split方法使用正則匹配將字符串切割成各子串并且返回
Matcher類:
注意,Matcher的獲得是通過(guò)Pattern.matcher(CharSequence charSequence);輸入必須是實(shí)現(xiàn)了CharSequence接口的類
常用方法:
matches()判斷整個(gè)輸入串是否匹配,整個(gè)匹配則返回true
例如下面會(huì)輸出true
String str1 = "hello";
Pattern pattern1 = Pattern.compile("hello");
Matcher matcher1 = pattern1.matcher(str1);
System.out.println(matcher1.matches());
lookingAt()從頭開(kāi)始尋找,找到匹配則返回true
例如下面會(huì)輸出true
String str2 = "hello yangfan!";
Pattern pattern2 = Pattern.compile("hello");
Matcher matcher2 = pattern2.matcher(str2);
System.out.println(matcher2.lookingAt());
find()掃描輸入串,尋找下一個(gè)匹配子串,存在則返回true
例如下面將會(huì)將所有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());