赛派号

香港电话号码格式886 大陆和香港手机号正则校验

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

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

大陆手机号匹配校验

/** * 大陆手机号码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); } }

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lsinopec@gmail.com举报,一经查实,本站将立刻删除。

上一篇 没有了

下一篇没有了