文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Java正则式的相关实例(2)—使用Ja..

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.替换首个匹配项

    }
}
 

相关阅读 更多 +
排行榜 更多 +
翌日波奇狗的历险记手机版下载

翌日波奇狗的历险记手机版下载

休闲益智 下载
怪兽远征安卓版下载

怪兽远征安卓版下载

角色扮演 下载
谷歌卫星地图免费版下载

谷歌卫星地图免费版下载

生活实用 下载