正则表达式——split、match,replaceAll基本用法

正则表达式

串中使用的API涉及正则
split
match
replaceAll

split

要求输出子串,没有空格

public class _正则表达式 {
    public static void main(String[] args) {
        String s = "abc  xyz kkk   ttt";//空格较多时,会产生空串

//     String ss[] = s.split(" {1,}");//" {1,}"正则写法,最少出现1次,最多出现任意多次(不写就是任意多次)
        String ss[] = s.split(" +");//" +"和上面是同一个意思
        //如果用+作分隔符,则必须转义,
        //----- "\\+" 表示 "+"
        //----- "\\{" 表示 "{"
        //----- "\\"  表示 "\"
        for(int i=0;i<ss.length;i++){
            System.out.println(ss[i]);
        }
    }
}

输出结果:

abc
xyz
kkk
ttt

match

匹配是否正确

/*
match
 */
public class _正则表达式02 {
    public static void main(String[] args) {
        String s ="AZ125";
        System.out.println(s.matches("[A-Z]{1,}[0-9]{1,}"));
        //"[A-Z]{1,}[0-9]{1,}" 表示 A到Z出现了1次到无穷次,0到9出现了1次到无穷次
    }
}

/*
可以用于:判断手机号,身份证号,年龄等一些需要用户输入的要素 ,防止用户输入明显错误的信息
[A-Z]{1,5}方括号表示出现的内容,大括号表示出现的次数(量词)

+  表示  {1,}  最少一次

*  表示  {0,}  任意多次

?  表示  {0,1} 零次或一次

 */

输出结果:

true

replaceAll

将2020-12-13转为13/12 2020年

public class 正则表达式03 {
    public static void main(String[] args) {
        String s="abckkd kj 2020-12-13 aa wdqwdasdzdlq";
        s=s.replaceAll("([0-9]{4})-([0-9]{2})-([0-9]{2})","$3/$2 $1年");
        //子组:在正则表达式中,用括号()括起来的部分称为子组
        //$1,表示第一个子组
        //$2,表示第二个子组
        System.out.println(s);
    }

}

输出结果:abckkd kj 13/12 2020年 aa wdqwdasdzdlq

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值