现有的微信小程序项目中需要实现登录界面手机号归属地的匹配,具体规则如下图(不是很清晰,将就一下):
这个项目需要实现国际手机号和归属地的判断,没试过这种开发一开始我也懵了,查找各种资料收集了三种方法和大家一起学习进步!
第一种:判断国内手机号格式验证及属于哪个运营商
package com.galaxy.platform.cornucopia.utils;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder;
import java.util.Locale;
import java.util.regex.Pattern;
/**
* @author liuzy
* @date 2020/5/25
*/
public class PhoneUtils {
/**
* 中国电信号码格式验证 手机段: 133,153,180,181,189,177,1700,173,199,191
**/
private static final String CHINA_TELECOM_PATTERN = "(^1(33|53|77|73|99|8[019]|9[1])\\d{8}$)|(^1700\\d{7}$)";
/**
* 中国联通号码格式验证 手机段:130,131,132,155,156,185,186,145,175,176,166,1709
**/
private static final String CHINA_UNICOM_PATTERN = "(^1(3[0-2]|4[5]|5[56]|6[6]|7[56]|8[56])\\d{8}$)|(^1709\\d{7}$)";
/**
* 中国移动号码格式验证
* 手机段:134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,198,1705
**/
private static final String CHINA_MOBILE_PATTERN = "(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478]|9[8])\\d{8}$)|(^1705\\d{7}$)";
/**
* 查询电话属于哪个运营商
*
* @param tel 手机号码
* @return 0:不属于任何一个运营商,1:移动,2:联通,3:电信
*/
public static Integer getPhoneISP(String tel) {
boolean b1 = tel == null || tel.trim().equals("") ? false : match(CHINA_MOBILE_PATTERN, tel);
if (b1) {
return 1;
}
b1 = tel == null || tel.trim().equals("") ? false : match(CHINA_UNICOM_PATTERN, tel);
if (b1) {
return 2;
}
b1 = tel == null || tel.trim().equals("") ? false : match(CHINA_TELECOM_PATTERN, tel);
if (b1) {
return 3;
}
return 0;
}
/**
* 匹配函数
* @param regex
* @param tel
* @return
*/
private static boolean match(String regex, String tel) {
return Pattern.matches(regex, tel);
}
public static String checkPhone(String tel) {
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumberOfflineGeocoder phoneNumberOfflineGeocoder = PhoneNumberOfflineGeocoder.getInstance();
String language ="CN";
Phonenumber.PhoneNumber referencePhonenumber = null;
try {
referencePhonenumber = phoneUtil.parse(tel