class Test {
/* 正则表达式实例
. 任何字符(与行结束符可能匹配也可能不匹配)
\d 数字:[0-9]
\D 非数字: [^0-9]
\s 空白字符:[ \t\n\x0B\f\r]
\S 非空白字符:[^\s]
\w 单词字符:[a-zA-Z_0-9]
\W 非单词字符:[^\w]
X? X,一次或一次也没有
X* X,零次或多次
X+ X,一次或多次
X{n} X,恰好 n 次
X{n,} X,至少 n 次
X{n,m} X,至少 n 次,但是不超过 m 次
捕获组可以通过从左到右计算其开括号来编号。例如,在表达式 ((A)(B(C))) 中,存在四个这样的组:
1 ((A)(B(C)))
2 \A
3 (B(C))
4 (C) */
//main方法
public static void main(String[] args) {
Test test = new Test();
//号码格式验证
test.matchesTelphone("138123456789"); //正确格式
test.matchesTelphone("13812345678"); //错误格式 长度不对
//字符串分割
test.splitString("大 家 晚上 好呀!");
//去除重复字
test.overlapString("大家家家家晚上上好呀");
}
public void matchesTelphone(String number){
//手机号码格式 1开头 第二个数字为 3或5或7或8 3到11位为数字即可
if(number.matches("1[3578]\\d{3,11}")){
System.out.println("the number is legal");
}
else{
System.out.println("the number is illegal");
}
}
public void splitString(String originalString){
//要求,按空格分割字符串
String[] string = originalString.split(" +");
System.out.println(Arrays.toString(string));
}
public void overlapString(String originalString){
//要求,去除重复字
String[] string = originalString.split("(.)\\1+");
System.out.println(Arrays.toString(string));
}
}