Java正则式的相关实例(2)—使用Ja..
时间:2010-09-11 来源:王守饼
上一篇介绍了两个使用第三方包进行正则式应用的实例,这里再给出使用Java API进行正则式应用的例子。java.util.regex包里对于正则表达式有很好的说明,详见API包。
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hfut.wst.regExp;
/**
*
* @author Administrator
*/
public class regExpOfJavaAPI {
public static void main(String[] args) {
java.util.regex.Pattern p = java.util.regex.Pattern.compile("(a*b)");
//尝试将整个输入序列与该模式匹配
java.util.regex.Matcher matcherTemp = p.matcher("aaaab");
boolean matchWhole = matcherTemp.matches();
java.util.regex.MatchResult resultWhole = matcherTemp.toMatchResult();
if (matchWhole) {
System.out.println("Match the Whole Sequence Successfully");
System.out.println(resultWhole.group(1));
}
//尝试将输入序列从头开始与该模式匹配
java.util.regex.Matcher matcherSub = p.matcher("aaab cd fs");
boolean matchSub = matcherSub.lookingAt();
java.util.regex.MatchResult resultSub = matcherSub.toMatchResult();
if (matchSub) {
System.out.println("Match the Sub Sequence Successfully");
System.out.println(resultSub.group(1));
}
//扫描输入序列以查找与该模式匹配的下一个子序列
java.util.regex.Matcher matchAll = p.matcher("aab df b r aaaaaab fg");
while (matchAll.find()) {
java.util.regex.MatchResult resultAll = matchAll.toMatchResult();
System.out.println("Match the All Sequence Successfully");
System.out.println(resultAll.group(1));
}
//实现相关替换操作
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("cat");
java.util.regex.Matcher m = pattern.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");//1.实现非终端添加和替换步骤
}
m.appendTail(sb);//2.实现终端添加和替换步骤
System.out.println(sb.toString());
System.out.println(m.replaceAll("dog"));//3.替换所有字串
System.out.println(m.replaceFirst("dog"));//4.替换首个匹配项
}
}