一、正则表达式主要是用于操作字符串的规则,正则表达式对字符串的操作主要有一下几种应用:
1、匹配:matches(String regex);
2、切割:split(String regex);
3、替换:replaceAll(String regex, String replacement);
4、查找:
二、匹配:
需求1:编写一个正则表达式匹配手机号(要求:第一位只能是1开头,第二位3、4、5、7、8,全是数字,长度11位)
public static void matchesPhone(String phone){
String reg = "1[34578]\\d{9}";
System.out.println(phone.matches(reg)?"手机号可以使用!":"手机号非法!");
}
需求2:匹配固定电话:区号-主机号(要求:区号:首位是0,长度:3~4。主机号:首位不能是0