正则表达式学习

首先贴上正则表达式全集

http://tool.oschina.net/uploads/apidocs/jquery/regexp.html

其次贴上学习正则前瞻,后顾匹配的链接

https://blog.csdn.net/csm0912/article/details/81206848

再贴上自己的学习代码

其一:分组匹配

/**
     * 正则匹配
     * 分组匹配
     */
    @Test
    void test1(){
        Pattern pattern=Pattern.compile(".*(cat).*(dog).*");
        Matcher matcher=pattern.matcher("one cat two dog in the yard");
        while (matcher.find()) {
            System.out.println(matcher.group());//等同于matcher.group(0),指对整个regex字符串的匹配
            System.out.println(matcher.group(1));//等同于第一个()中的内容
            System.out.println(matcher.group(2));//等同于第二个()中的内容
        }
    }

其二:分组匹配并替换指定格式的字符串

/**
     * 正则匹配
     * 分组匹配并替换指定格式的字符串
     */
@Test
    void test2(){
        Pattern pattern2=Pattern.compile("\\$\\{(\\w+)}");
        String str="one ${CAT} two ${DOG} in the yard";
        Map<String,String> map= new HashMap<>();
        map.put("CAT","cat");
        Matcher matcher2=pattern2.matcher(str);
        StringBuffer stringBuffer = new StringBuffer();
        while (matcher2.find()){
            String find=matcher2.group();
            String var=find.substring(2,find.length()-1);
            //替换str中的匹配的出来的字符串至stringBuffer中
            matcher2.appendReplacement(stringBuffer,map.get(var)==null?"xxx":map.get(var));
        }
        System.out.println(stringBuffer.toString());
        //将待匹配str中剩余的无需匹配的尾巴补上
        matcher2.appendTail(stringBuffer);
        System.out.println(stringBuffer.toString());
    }

其三:前瞻正则 exp1(?=exp2)

/**
     * 前瞻正则 查找exp2前面的exp1  目标为exp1
     * exp1(?=exp2)
     */
    @Test
    void test3(){
        String string="我是一个中国人";
        System.out.println(string.replaceAll("中国(?=人)","xxx"));
    }

其四:后顾正则 (?<=exp2)exp1

/**
     * 后顾正则 查找exp2后面的exp1
     * (?<=exp2)exp1
     */
    @Test
    void test4(){
        String string="我是一个中国人";
        System.out.println(string.replaceAll("(?<=一个)中国","xxx"));
    }

其五:负前瞻正则 exp1(?!exp2)

/**
     * 负前瞻  查询后面不是exp2的exp1
     * exp1(?!exp2)
     */
    @Test
    void test5(){
        String string="我是一个中国人";
        System.out.println(string.replaceAll("中国(?!yyyy)","xxx"));
    }

其六:负后顾正则 (?<!exp2)exp1

/**
     * 负后顾  查询前面不是exp2的exp1
     * (?<!exp2)exp1
     */
    @Test
    void test6(){
        String string="我是一个中国人";
        System.out.println(string.replaceAll("(?<!yyy)中国","xxx"));
    }

最后贴上记忆的方法

  • 所谓前瞻exp1(?=exp2),那么使用的时候,即目标是exp1,即将exp1放前面,接着放(?=),就好了。
  • 后顾的话,目标exp2放括号后面就行。
  • 如何写前瞻还是负前瞻呢,那么只用将表达式中的=替换为!即可。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值