Home  >  Article  >  Java  >  Java regular expression to determine whether it is a mobile phone number code

Java regular expression to determine whether it is a mobile phone number code

PHPz
PHPzOriginal
2017-04-03 10:14:133058browse

在开发中有时会有这样的需求,就是判断用户输入的手机号码是否正确,这里就需要使用到了正则表达式。

这里贴出一个电话号码检查的工具类,基本的电话号码格式都能够满足了。

import java.util.regex.Matcher;  
import java.util.regex.Pattern;  
import java.util.regex.PatternSyntaxException;  
  
public class PhoneFormatCheckUtils {  
  
    /** 
     * 大陆号码或香港号码均可 
     */  
    public static boolean isPhoneLegal(String str)throws PatternSyntaxException {  
        return isChinaPhoneLegal(str) || isHKPhoneLegal(str);  
    }  
  
    /** 
     * 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数 
     * 此方法中前三位格式有: 
     * 13+任意数 
     * 15+除4的任意数 
     * 18+除1和4的任意数 
     * 17+除9的任意数 
     * 147 
     */  
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {  
        String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\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 {  
        String regExp = "^(5|6|8|9)\\d{7}$";  
        Pattern p = Pattern.compile(regExp);  
        Matcher m = p.matcher(str);  
        return m.matches();  
    }  
      
}

当然,这里使用正则表达式不一定都面面俱到了,以后万一又有什么新的格式了也不好说,不过道理都是一样的,修改一下正则表达式的规则就行。

The above is the detailed content of Java regular expression to determine whether it is a mobile phone number code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn