正则表达式对手机号码进行校验
代码如下
/*
* 对手机号码进行校验 *
* 移动号段: 134 135 136 137 138 139 147 148 150 151 152 157 158 159 172
* 178 182 183 184 187 188 198
* 联通号段: 130 131 132 145 146 155 156 166 171 175 176
* 185 186
* 电信号段: 133 149 153 173 174 177 180 181 189 199
* 虚拟运营商: 170
*/
public class TestPhone {
public static void main(String[] args) {
String str = "18974555356";
// 以哪些数字开头
// String regex =
// "^((13[0-9])|(14[56789])|(15[0-9])|(17[0-9])(18[0-9])|(19[89]))\\d{8}$";
String regex = "^((13[0-9])|(14[5|7|9])|(15([0-9])|(17[0-9])|(18[0-9])|(19[8|9]))\\d{8})$";
// 创建一个匹配模式
Pattern p = Pattern.compile(regex);
// 返回matcher对象
Matcher m = p.matcher(str);
//判断是否匹配指定的字符串
boolean isMatch = m.matches();
if (isMatch) {
System.out.println("手机号输入正确!");
} else {
System.err.println("手机号码输入错误");
}
}
}
注:主要是对手机号的前三位有限制,利用正则表达式判断是否符合要求,|可省去