码迷,mamicode.com
首页 > 编程语言 > 详细

Java正则验证

时间:2015-11-12 19:37:20      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

 1     /**
 2      * 验证手机号.
 3      * 
 4      * @param phone the phone
 5      * @return true, if successful
 6      */
 7     public static boolean isPhone(String phone){
 8         if(StringUtils.isBlank(phone)){
 9             return false;
10         }
11         String regex = "^[1][3,4,5,8][0-9]{9}$";
12         Pattern p = Pattern.compile(regex);
13         Matcher m = p.matcher(phone);
14         return m.matches();
15     }
 1     /**
 2      * 验证身份证号是否合法(只验证18位).
 3      *
 4      * @param idCard the id card
 5      * @return true, if is id card
 6      */
 7     public static boolean isIdCard(String idCard){
 8         String regex = "(((1[1-5])|(2[1-3])|(3[1-7])|(4[1-6])|(5[0-4])|(6[1-5])|71|(8[12])|91)\\d{4}((19\\d{2}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|(19\\d{2}(0[13578]|1[02])31)|(19\\d{2}02(0[1-9]|1\\d|2[0-8]))|(19([13579][26]|[2468][048]|0[48])0229))(\\d{3})(\\d|X|x))";
 9         int[] factorArray = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
10         String[] parityBit = new String[]{"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
11         String[] idArray = new String[18];
12         int intStrLen = idCard.length();
13         String idStr = idCard;
14         int sum = 0;
15         
16         //正则验证身份证格式是否正确
17         Pattern pattern = Pattern.compile(regex);
18         Matcher matcher = pattern.matcher(idCard);
19         if(!matcher.matches()){
20             return false;
21         }
22         
23         //验证身份证号算法是否合法
24         for(int i = 0; i < intStrLen; i ++){
25             idArray[i] = idStr.charAt(i) + "";
26             if(i < (intStrLen - 1)){
27                 sum += factorArray[i] * Integer.parseInt(idArray[i]);
28             }
29         }
30         if(!parityBit[(sum % 11)].equalsIgnoreCase(idArray[intStrLen - 1])){
31             return false;
32         }
33         return true;
34     }

 

Java正则验证

标签:

原文地址:http://www.cnblogs.com/thierry/p/4959745.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!