前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java验证手机号

Java验证手机号

作者头像
GreizLiao
发布2019-09-24 16:10:39
2.1K0
发布2019-09-24 16:10:39
举报
文章被收录于专栏:足球是圆的足球是圆的

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

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);
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-01-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档