正则表达式
串中使用的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