正则表达式1-基础用法

/**
 * @author
 * @version v1.0
 * @description 替换字符串内部空格  trim()是去掉首尾空格
 * @date 2020/1/10
 */
public class Test {

    public static void main(String[] args) {

        String ss = "[1,  2,    4]";
        System.out.println(ss.replaceAll("\\s+", ""));
        System.out.println(ss.replaceAll(" +", ""));
        System.out.println(ss.replaceAll(" ", ""));
        System.out.println(ss.replaceAll(" {1,}", ""));
    }
}

 

/**
 * @author
 * @version v1.0
 * @description 正则表达式中^的用法
 * @date 2020/1/10
 */
public class RegexTest {

    public static void main(String[] args) {

        /**
         * 正则表达式中^的用法
         */
        //1、限定开头
        String str1 = "[1,2]";
        String str2 = "3[1,2]";
        //匹配以[开头的元素
        System.out.println(Pattern.matches("^\\[\\d,\\d]", str1));//true
        System.out.println(Pattern.matches("^\\[\\d,\\d]", str2));//false

        //2、(否)取反
        // 当这个字符出现在一个字符集合模式的第一个字符时,他将会有不同的含义。
        String str3 = "2020 is coming HAPPY";
        //匹配不是(a到z和空白字符)的字符
        String regex = "[^a-z\\s]";
        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(str3);
        System.out.println(matcher.groupCount()); //0
        while (matcher.find()) {
            System.out.println(matcher.group(0));
            System.out.println(matcher.group());
            System.out.println("----------------------------------------------");
        }
        /**
         * 2
         * 2
         * ----------------------------------------------
         * 0
         * 0
         * ----------------------------------------------
         * 2
         * 2
         * ----------------------------------------------
         * 0
         * 0
         * ----------------------------------------------
         * H
         * H
         * ----------------------------------------------
         * A
         * A
         * ----------------------------------------------
         * P
         * P
         * ----------------------------------------------
         * P
         * P
         * ----------------------------------------------
         * Y
         * Y
         * ----------------------------------------------
         */

    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值