黑马程序员技术交流社区
标题:
如何验证号码有效性?
[打印本页]
作者:
耿渊博
时间:
2014-3-24 00:22
标题:
如何验证号码有效性?
以下代码是验证电话号码有效性,大家看看还有更好的方法
public class CheckPhoneNum {
public static void main(String[] args) {
// TODO Auto-generated method stub
String phoneNum = "0431-89526232188";
System.out.println(check(phoneNum));
}
public static String check(String text){
if(text == null || text.isEmpty()){
return"请输入号码!";
}
String regex = "^\\d{3}-?\\d{8}\\d{4}-?d{8}$";
if(text.matches(regex)){
return text + "\n 是一个合法的电话号码!";
}else{
return text + "\n不是一个合法的电话号码!";
}
}
}
复制代码
作者:
papercup
时间:
2014-3-24 10:49
好像很厉害的样子!可是有点看不懂额。。。。
作者:
霍振鹏
时间:
2014-3-25 00:32
楼主说一下规则么,什么号码就算合法了?
作者:
李东梁
时间:
2014-3-25 10:46
/**
* <pre>
Const为常量类或接口
String TEL_MOBILE = config.get("TEL_MOBILE", "134,135,136,137,138,139,150,158,159"); //移动的号码段
String TEL_UNICOM = config.get("TEL_UNICOM", "130,131,132,133,153,156"); //联通的号码段
* 号码段放入配置文件,目前(2007-10-11)的号码段为:
* 移动:134,135,136,137,138,139,150,158,159
* 联通:130,131,132,133,153,156
* </pre>
* @param tel
* @return 运营商 (1=移动、2=联通)
*/
public static byte getTelCompany(String tel)
{
String telHead = tel.substring(0, 3);
if(isMobileUnicom(telHead,1))
{
return 1;
}
if(isMobileUnicom(telHead,2))
{
return 2;
}
return -1;
}
private static boolean isMobileUnicom(String telHead,int company)
{
String tel = "";
switch(company)
{
case 1:
tel = Const.TEL_MOBILE;
break;
case 2:
tel = Const.TEL_UNICOM;
break;
default:
return false;
}
String[] aTel = tel.split(",");
int iCount = aTel.length;
for(int i=0;i<iCount;i++)
{
if (aTel[i].equals(telHead))
{
return true;
}
}
return false;
}
复制代码
作者:
赵彦丰
时间:
2014-3-25 10:49
本帖最后由 赵彦丰 于 2014-3-25 10:54 编辑
用用这个
"^[1][358]\\d{9}[ DISCUZ_CODE_0 ]quot;
复制代码
1代表第一位 358代表第二位 后面跟9位数字 都是13 15 18 号段的 简单得验证
public static boolean isMobileNO(String mobiles) {
Pattern p = Pattern
.compile("^[1][358]\\d{9}[ DISCUZ_CODE_0 ]quot;);
Matcher m = p.matcher(mobiles);
System.out.println(m.matches() + "---");
return m.matches();
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2