Java验证手机号

在实际开发中我们需要对手机号格式校验,以下是对中国手机号校验的实现。

public class PhoneUtils {

    /**
     * 中国手机号码
     */
    private static Pattern CHINESE_PHONE_PATTERN = Pattern.compile("((13|15|17|18)\\d{9})|(14[57]\\d{8})");

    
    /**
     * 是否是有效的中国手机号码
     * @param phone
     * @return
     */
    public static boolean isValidChinesePhone(String phone) {
        if (phone == null || phone.length() != 11) {
            return false;
        }
        
        Matcher matcher = CHINESE_PHONE_PATTERN.matcher(phone);
        return matcher.matches();
    }
    
    
    /**
     * 检查手机是否无效
     * @param phone
     * @return
     */
    public static boolean isNotValidChinesePhone(String phone) {
        return !isValidChinesePhone(phone);
    }
    
    
    /**
     * 手机中间添加星号
     * @param phone
     * @param beginIndex
     * @param endIndex
     * @return empty string if phone length is illegal
     */
    public static String setAsterisk(String phone, int beginIndex, int endIndex) {
        
        if (StringUtils.isBlank(phone)) {
            return StringUtils.EMPTY;
        }
        
        if (beginIndex < 0 || endIndex < 0 || beginIndex > phone.length() || endIndex > phone.length()) {
            throw new IllegalArgumentException("illegal index " + beginIndex + "," + endIndex);
        }
        
        StringBuilder phoneWithAsterisk = new StringBuilder(phone.substring(0, beginIndex));  
        
        for (int i = beginIndex; i < endIndex; i++) {  
            phoneWithAsterisk.append("*");  
        }  
        
        phoneWithAsterisk.append(phone.substring(endIndex, phone.length()));
        return phoneWithAsterisk.toString();
    }
    
    /**
     * 手机中间添加星号
     * @param phone
     * @return
     */
    public static String setAsterisk(String phone) {
        return setAsterisk(phone, 3, 7);
    }

    /**
     * 手机中间添加星号,中间六位
     * @param phone
     * @return
     */
    public static String setAsterisk2(String phone) {
        return setAsterisk(phone, 3, 9);
    }
}

转载于:https://www.cnblogs.com/wolf-bin/p/8177260.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值