大陆和香港手机号正则校验 您所在的位置:网站首页 香港地区电话开头 大陆和香港手机号正则校验

大陆和香港手机号正则校验

2024-07-01 11:25| 来源: 网络整理| 查看: 265

大陆和香港手机号正则校验

在日常的开发中,经常会遇到需要校验手机号的情况,这里列举大陆和香港的手机校验。

大陆手机号匹配校验

/** * 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数 * 此方法中前三位格式有: * 13+任意数 * 145,147,149 * 15+除4的任意数(不要写^4,这样的话字母也会被认为是正确的) * 166 * 17+3,5,6,7,8 * 18+任意数 * 198,199 */ public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException { // ^ 匹配输入字符串开始的位置 // \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d // $ 匹配输入字符串结尾的位置 String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" + "|(18[0-9])|(19[8,9]))\\d{8}$"; Pattern p = Pattern.compile(regExp); Matcher m = p.matcher(str); return m.matches(); }

香港手机号匹配校验

/** * 香港手机号码8位数,5|6|8|9开头+7位任意数 */ public static boolean isHKPhoneLegal(String str) throws PatternSyntaxException { // ^ 匹配输入字符串开始的位置 // \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d // $ 匹配输入字符串结尾的位置 String regExp = "^(5|6|8|9)\\d{7}$"; Pattern p = Pattern.compile(regExp); Matcher m = p.matcher(str); return m.matches(); }

同时校验大陆和香港号码

/** * 大陆号码或香港号码均可 */ public static boolean isPhoneLegal(String str) throws PatternSyntaxException { return isChinaPhoneLegal(str) || isHKPhoneLegal(str); }

使用 在app的注册功能中,我们想实现对注册的手机号进行校验,没有通过的手机号不可注册。

if(checkUser(userNameText.getText().toString())){ registerErrorText.setText(R.string.used_username); registerErrorText.setVisibility(View.VISIBLE); Log.d(TAG,"该用户名已经被注册"); }else{ if(!PhoneFormatCheckUtils.isPhoneLegal(userNameText.getText().toString())){ registerErrorText.setText(R.string.standardtel); registerErrorText.setVisibility(View.VISIBLE); Log.d(TAG,"手机号码不正确"); }else{ registerErrorText.setVisibility(View.INVISIBLE); RegisterButton.setEnabled(true); RegisterButton.setClickable(true); } }

效果 在这里插入图片描述 输入手机号短 在这里插入图片描述

输入正确的手机号码即可注册。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有