PhoneFormatCheckUtils.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package com.aijia.utils;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. import java.util.regex.PatternSyntaxException;
  5. public class PhoneFormatCheckUtils {
  6. /**
  7. * ^ 匹配输入字符串开始的位置
  8. * \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d
  9. * $ 匹配输入字符串结尾的位置
  10. */
  11. private static final Pattern HK_PATTERN = Pattern.compile("^(5|6|8|9)\\d{7}$");
  12. private static final Pattern CHINA_PATTERN = Pattern.compile("^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\\d{8}$");
  13. private static final Pattern NUM_PATTERN = Pattern.compile("[0-9]+");
  14. /**
  15. * 大陆号码或香港号码均可
  16. */
  17. public static boolean isPhoneLegal(String str) throws PatternSyntaxException {
  18. return isChinaPhoneLegal(str) || isHKPhoneLegal(str);
  19. }
  20. /**
  21. * 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数
  22. * 此方法中前三位格式有:
  23. * 13+任意数
  24. * 145,147,149
  25. * 15+除4的任意数(不要写^4,这样的话字母也会被认为是正确的)
  26. * 166
  27. * 17+3,5,6,7,8
  28. * 18+任意数
  29. * 198,199
  30. */
  31. public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
  32. Matcher m = CHINA_PATTERN.matcher(str);
  33. return m.matches();
  34. }
  35. /**
  36. * 香港手机号码8位数,5|6|8|9开头+7位任意数
  37. */
  38. public static boolean isHKPhoneLegal(String str) throws PatternSyntaxException {
  39. Matcher m = HK_PATTERN.matcher(str);
  40. return m.matches();
  41. }
  42. /**
  43. * 判断是否是正整数的方法
  44. */
  45. public static boolean isNumeric(String string) {
  46. return NUM_PATTERN.matcher(string).matches();
  47. }
  48. }