您的位置:首页 > 编程语言 > Java开发

Java正则表达式——验证手机号和电话号码

2016-12-05 16:44 351 查看
一个朋友需要,所以写了这两个,话不都说,看代码

/**
* 获取当前的httpSession
* @author :shijing
* 2016年12月5日下午3:46:02
* @return
*/
public static HttpSession getSession() {
return getRequest().getSession();
}

/**
* 手机号验证
* @author :shijing
* 2016年12月5日下午4:34:46
* @param str
* @return 验证通过返回true
*/
public static boolean isMobile(final String str) {
Pattern p = null;
Matcher m = null;
boolean b = false;
p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
m = p.matcher(str);
b = m.matches();
return b;
}
/**
* 电话号码验证
* @author :shijing
* 2016年12月5日下午4:34:21
* @param str
* @return 验证通过返回true
*/
public static boolean isPhone(final String str) {
Pattern p1 = null, p2 = null;
Matcher m = null;
boolean b = false;
p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 验证带区号的
p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$"); // 验证没有区号的
if (str.length() > 9) {
m = p1.matcher(str);
b = m.matches();
} else {
m = p2.matcher(str);
b = m.matches();
}
return b;
}

public static void main(String[] args) {
String phone = "13900442200";
String phone2 = "021-88889999";
String phone3 = "88889999";
String phone4 = "1111111111";
//测试1
if(isPhone(phone) || isMobile(phone)){
System.out.println("1这是符合的");
}
//测试2
if(isPhone(phone2) || isMobile(phone2)){
System.out.println("2这是符合的");
}
//测试3
if(isPhone(phone3) || isMobile(phone3)){
System.out.println("3这是符合的");
}
//测试4
if(isPhone(phone4) || isMobile(phone4)){
System.out.println("4这是符合的");
}else{
System.out.println("不符合");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐