要求的手机号码:
1.号码位数只有11位
2.不能出现字母或其他字符
3.一般以13x 15x 18x开头
通过正则表达式校验:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Test
public void test() {
Pattern pattern = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9]))\\d{8}$+");
// phone1 正常号码
String phone1 = "13875401431";
// phone2 加入字符
String phone2 = "1387cc01431";
// phone3 号码位数为10位
String phone3 = "138740143";
Matcher matcher1 = pattern.matcher(phone1);
Matcher matcher2 = pattern.matcher(phone2);
Matcher matcher3 = pattern.matcher(phone3);
if (matcher1.find()) {
System.out.println(matcher1.group()); // 输出成功:13875401431
}
if (matcher2.find()) { // 找不到
System.out.println(matcher2.group());
}
if (matcher3.find()) { // 找不到
System.out.println(matcher3.group());
}
}
暴力方法(ACSII):
String isPhone = "18874014311";
int index = 11;
if (StrUtil.isEmpty(isPhone) || isPhone.length() != index) {
return "请输入正确的电话号码";
}
for (int i=0; i<isPhone.length();i++) {
if (isPhone.charAt(i) == ' ' || (isPhone.charAt(i) >= 97 &&
isPhone.charAt(i) <= 122) || (isPhone.charAt(i) >= 65 && isPhone.charAt(i) <= 90)) {
return "请输入正确的电话号码";
}
}
这个只适合用户号码位数和是否含有字母进行判断,无法校验号码开头