Java common regular expression validation tool class RegexUtils.java

  • 2020-05-12 02:42:15
  • OfStack

Regular expressions are often used to validate various forms. The Java form registers the commonly used regular expression validation utility class, a large collection of commonly used regular expressions.

1. Phone number

2. Zip code

3. QQ

4. E-mail

5. Cell phone number

6. URL

7. Whether it is a number

8. Whether it is in Chinese

9. Your id card

Domain names 10.

11. IP...

Common validation has everything! This is really your web development, server-side form validation good! You deserve to have ^_^


/*
 *  Copyright 2012-2013 The Haohui Network Corporation
 */
package com.haohui.common.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @project baidamei
 * @author cevencheng <cevencheng@gmail.com>
 * @create 2012-11-15  In the afternoon 4:54:42
 */
public class RegexUtils {

   /**
   *  validation Email
   * @param email email Address, format: zhangsan@zuidaima.com . zhangsan@xxx.com.cn . xxx On behalf of a mail service provider 
   * @return  Verify successful return true , returned after validation failure false
   */ 
  public static boolean checkEmail(String email) { 
    String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; 
    return Pattern.matches(regex, email); 
  } 
   
  /**
   *  Verification of id card number 
   * @param idCard  Id card number 15 or 18 And the last 1 Bits may be Numbers or letters 
   * @return  Verify successful return true , returned after validation failure false
   */ 
  public static boolean checkIdCard(String idCard) { 
    String regex = "[1-9]\\d{13,16}[a-zA-Z0-9]{1}"; 
    return Pattern.matches(regex,idCard); 
  } 
   
  /**
   *  Verify mobile phone number (supports international format, +86135xxxx... (mainland China), +00852137xxxx... (Hong Kong, China) 
   * @param mobile  The number segment of mobile, unicom and telecom operators 
   *<p> Mobile segment: 134(0-8) , 135 , 136 , 137 , 138 , 139 , 147 (intended for TD Card) 
   * , 150 , 151 , 152 , 157 ( TD Dedicated), 158 , 159 , 187 (not enabled), 188 ( TD Special) </p>
   *<p> Unicom's number segment: 130 , 131 , 132 , 155 , 156 (for world wind), 185 (not enabled), 186 ( 3g ) </p>
   *<p> Telecom segment: 133 , 153 , 180 (not enabled), 189</p>
   * @return  Verify successful return true , returned after validation failure false
   */ 
  public static boolean checkMobile(String mobile) { 
    String regex = "(\\+\\d+)?1[34578]\\d{9}$"; 
    return Pattern.matches(regex,mobile); 
  } 
   
  /**
   *  Verify the landline number 
   * @param phone  Telephone number, format: country (region) telephone code  +  Area code (city code)  +  Telephone number such as: +8602085588447
   * <p><b> Country (region)   code   : </b> The standard country code for the country (region) in which the telephone number is identified. It contains from  0  to  9  the 1 Bits or Numbers, 
   *  The number is followed by a space-delimited country code. </p>
   * <p><b> Area code (city code) : </b> This might include 1 One or more from  0  to  9  The number of the region or city code placed in parentheses -- 
   *  For countries that do not use a region or city code, the component is omitted. </p>
   * <p><b> Telephone no. : </b> This includes from  0  to  9  the 1 Number or Numbers  </p>
   * @return  Verify successful return true , returned after validation failure false
   */ 
  public static boolean checkPhone(String phone) { 
    String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$"; 
    return Pattern.matches(regex, phone); 
  } 
   
  /**
   *  Validate integers (positive and negative) 
   * @param digit 1 One or more 0-9 Integer between 
   * @return  Verify successful return true , returned after validation failure false
   */ 
  public static boolean checkDigit(String digit) { 
    String regex = "\\-?[1-9]\\d+"; 
    return Pattern.matches(regex,digit); 
  } 
   
  /**
   *  Validate integers and floating point Numbers (plus or minus integers and plus or minus floating point Numbers) 
   * @param decimals 1 One or more 0-9 A floating point number between, such as: 1.23 . 233.30
   * @return  Verify successful return true , returned after validation failure false
   */ 
  public static boolean checkDecimals(String decimals) { 
    String regex = "\\-?[1-9]\\d+(\\.\\d+)?"; 
    return Pattern.matches(regex,decimals); 
  } 
   
  /**
   *  Validate white space character 
   * @param blankSpace  White space characters, including: Spaces, \t , \n , \r , \f , \x0B
   * @return  Verify successful return true , returned after validation failure false
   */ 
  public static boolean checkBlankSpace(String blankSpace) { 
    String regex = "\\s+"; 
    return Pattern.matches(regex,blankSpace); 
  } 
   
  /**
   *  Verify the Chinese 
   * @param chinese  Chinese characters 
   * @return  Verify successful return true , returned after validation failure false
   */ 
  public static boolean checkChinese(String chinese) { 
    String regex = "^[\u4E00-\u9FA5]+$"; 
    return Pattern.matches(regex,chinese); 
  } 
   
  /**
   *  Validation date (year, month, day) 
   * @param birthday  Date, format: 1992-09-03 Or, 1992.09.03
   * @return  Verify successful return true , returned after validation failure false
   */ 
  public static boolean checkBirthday(String birthday) { 
    String regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}"; 
    return Pattern.matches(regex,birthday); 
  } 
   
  /**
   *  validation URL address 
   * @param url  Format: http://blog.csdn.net:80/xyang81/article/details/7705960?  or  http://www.csdn.net:80
   * @return  Verify successful return true , returned after validation failure false
   */ 
  public static boolean checkURL(String url) { 
    String regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=.*)?)?"; 
    return Pattern.matches(regex, url); 
  } 
  
  /**
   * <pre>
   *  Access to the website  URL  the 1 Level domain 
   * </pre>
   * 
   * @param url
   * @return
   */
  public static String getDomain(String url) {
    Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE);
    //  Get the full domain name 
    // Pattern p=Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE);
    Matcher matcher = p.matcher(url);
    matcher.find();
    return matcher.group();
  }
  /**
   *  Match China zip code 
   * @param postcode  The zip code 
   * @return  Verify successful return true , returned after validation failure false
   */ 
  public static boolean checkPostcode(String postcode) { 
    String regex = "[1-9]\\d{5}"; 
    return Pattern.matches(regex, postcode); 
  } 
   
  /**
   *  matching IP address ( Simple matching, format, such as: 192.168.1.1 . 127.0.0.1 , no match IP The size of the segment )
   * @param ipAddress IPv4 Standard address 
   * @return  Verify successful return true , returned after validation failure false
   */ 
  public static boolean checkIpAddress(String ipAddress) { 
    String regex = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))"; 
    return Pattern.matches(regex, ipAddress); 
  } 
   
}

Share a utility class that USES regular expressions to validate phone Numbers, id Numbers, date formats, URL, Email, and so on


package com.eabax.util;
 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
 
/**
 *  Validation tool class 
 * @author admin
 *
 */
public class Validation { 
  //------------------ Constants defined  
  /** 
   * Email Regular expression ="^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
   */
  //public static final String EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";; 
  public static final String EMAIL = "\\w+(\\.\\w+)*@\\w+(\\.\\w+)+";
  /** 
   *  Regular expressions for phone Numbers = (^(\d{2,4}[-_ - - ]?)?\d{3,8}([-_ - - ]?\d{3,8})?([-_ - - ]?\d{1,7})?$)|(^0?1[35]\d{9}$) 
   */
  public static final String PHONE = "(^(\\d{2,4}[-_ - - ]?)?\\d{3,8}([-_ - - ]?\\d{3,8})?([-_ - - ]?\\d{1,7})?$)|(^0?1[35]\\d{9}$)" ; 
  /** 
   *  Regular expressions for cell phone Numbers =^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$
   */
  public static final String MOBILE ="^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\\d{8}$"; 
 
  /** 
   * Integer Regular expression  ^-?(([1-9]\d*$)|0) 
   */
  public static final String INTEGER = "^-?(([1-9]\\d*$)|0)"; 
  /** 
   *  Positive integer regular expression  >=0 ^[1-9]\d*|0$ 
   */
  public static final String INTEGER_NEGATIVE = "^[1-9]\\d*|0$"; 
  /** 
   *  Negative integer regular expression  <=0 ^-[1-9]\d*|0$ 
   */
  public static final String INTEGER_POSITIVE = "^-[1-9]\\d*|0$";   
  /** 
   * Double Regular expression  ^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$ 
   */
  public static final String DOUBLE ="^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)$"; 
  /** 
   *  is Double Regular expression  >=0 ^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$  
   */
  public static final String DOUBLE_NEGATIVE ="^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0$"; 
  /** 
   *  negative Double Regular expression  <= 0 ^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$ 
   */
  public static final String DOUBLE_POSITIVE ="^(-([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*))|0?\\.0+|0$";  
  /** 
   *  Age regular expression  ^(?:[1-9][0-9]?|1[01][0-9]|120)$  matching 0-120 At the age of  
   */
  public static final String AGE="^(?:[1-9][0-9]?|1[01][0-9]|120)$"; 
  /** 
   *  Postcode regular expression  [0-9]\d{5}(?!\d)  domestic 6 A zip code  
   */
  public static final String CODE="[0-9]\\d{5}(?!\\d)";  
  /** 
   *  Match by number, 26 A string of letters or underscores  ^\w+$ 
   */
  public static final String STR_ENG_NUM_="^\\w+$"; 
  /** 
   *  Match by number and 26 A string of four English letters  ^[A-Za-z0-9]+$ 
   */
  public static final String STR_ENG_NUM="^[A-Za-z0-9]+"; 
  /** 
   *  Matched by 26 A string of four English letters  ^[A-Za-z]+$ 
   */
  public static final String STR_ENG="^[A-Za-z]+$"; 
  /** 
   *  Filter special string regularization  
   * regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~ ! @# RMB % ... &* () - +|{} 【 】 '; : "" ' . ,,? ]"; 
   */
  public static final String STR_SPECIAL="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~ ! @# RMB % ... &* () - +|{} 【 】 '; : "" ' . ,,? ]"; 
  /*** 
   *  The date of the regular   Support:  
   * YYYY-MM-DD 
   * YYYY/MM/DD 
   * YYYY_MM_DD 
   * YYYYMMDD 
   * YYYY.MM.DD In the form of  
   */
  public static final String DATE_ALL="((^((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/\\._]?)(10|12|0?[13578])([-\\/\\._]?)(3[01]|[12][0-9]|0?[1-9])$)" + 
      "|(^((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/\\._]?)(11|0?[469])([-\\/\\._]?)(30|[12][0-9]|0?[1-9])$)" + 
      "|(^((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/\\._]?)(0?2)([-\\/\\._]?)(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)([-\\/\\._]?)(0?2)([-\\/\\._]?)(29)$)|(^([3579][26]00)" + 
      "([-\\/\\._]?)(0?2)([-\\/\\._]?)(29)$)" + 
      "|(^([1][89][0][48])([-\\/\\._]?)(0?2)([-\\/\\._]?)(29)$)|(^([2-9][0-9][0][48])([-\\/\\._]?)" + 
      "(0?2)([-\\/\\._]?)(29)$)" + 
      "|(^([1][89][2468][048])([-\\/\\._]?)(0?2)([-\\/\\._]?)(29)$)|(^([2-9][0-9][2468][048])([-\\/\\._]?)(0?2)" + 
      "([-\\/\\._]?)(29)$)|(^([1][89][13579][26])([-\\/\\._]?)(0?2)([-\\/\\._]?)(29)$)|" + 
      "(^([2-9][0-9][13579][26])([-\\/\\._]?)(0?2)([-\\/\\._]?)(29)$))"; 
  /*** 
   *  The date of the regular   Support:  
   * YYYY-MM-DD 
   */
  public static final String DATE_FORMAT1="(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";
   
  /** 
   * URL Regular expression  
   *  matching  http www ftp 
   */
  public static final String URL = "^(http|www|ftp|)?(://)?(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*((:\\d+)?)(/(\\w+(-\\w+)*))*(\\.?(\\w)*)(\\?)?" + 
                  "(((\\w*%)*(\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*(\\w*%)*(\\w*\\?)*" + 
                  "(\\w*:)*(\\w*\\+)*(\\w*\\.)*" + 
                  "(\\w*&)*(\\w*-)*(\\w*=)*)*(\\w*)*)$";  
 
  /** 
   *  Id regular expression  
   */
  public static final String IDCARD="((11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|50|51|52|53|54|61|62|63|64|65)[0-9]{4})" + 
                    "(([1|2][0-9]{3}[0|1][0-9][0-3][0-9][0-9]{3}" + 
                    "[Xx0-9])|([0-9]{2}[0|1][0-9][0-3][0-9][0-9]{3}))";
   
  /**
   *  Organization code 
   */
  public static final String JIGOU_CODE = "^[A-Z0-9]{8}-[A-Z0-9]$";
   
  /**
   *  A string of matching Numbers  ^[0-9]+$ 
   */
  public static final String STR_NUM = "^[0-9]+$"; 
    
////------------------ Validation method     
  /** 
   *  Determines if the field is empty   In return ture 
   * @param str 
   * @return boolean 
   */
  public static synchronized boolean StrisNull(String str) { 
    return null == str || str.trim().length() <= 0 ? true : false ; 
  } 
  /** 
   *  Determine that the field is not empty   In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean StrNotNull(String str) { 
    return !StrisNull(str) ; 
  } 
  /** 
   *  string null Turn the empty  
   * @param str 
   * @return boolean 
   */
  public static String nulltoStr(String str) {
    return StrisNull(str)?"":str; 
  }   
  /** 
   *  string null Assign default values  
   * @param str   Target string  
   * @param defaut  The default value  
   * @return String 
   */
  public static String nulltoStr(String str,String defaut) { 
    return StrisNull(str)?defaut:str; 
  } 
  /** 
   *  Determine whether the field is Email  In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isEmail(String str) { 
    return Regular(str,EMAIL); 
  } 
  /** 
   *  Determine if it is a phone number   In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isPhone(String str) { 
    return Regular(str,PHONE); 
  } 
  /** 
   *  Determine if it is a mobile phone number   In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isMobile(String str) { 
    return Regular(str,MOBILE); 
  } 
  /** 
   *  Judge whether Url  In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isUrl(String str) { 
    return Regular(str,URL); 
  }   
  /** 
   *  Determines whether the field is a number   The positive and negative integers   Floating point number   In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isNumber(String str) { 
    return Regular(str,DOUBLE); 
  } 
  /** 
   *  Determine whether the field is INTEGER  In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isInteger(String str) { 
    return Regular(str,INTEGER); 
  } 
  /** 
   *  Determines whether the field is a positive integer regular expression  >=0  In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isINTEGER_NEGATIVE(String str) { 
    return Regular(str,INTEGER_NEGATIVE); 
  } 
  /** 
   *  Determines whether the field is a negative integer regular expression  <=0  In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isINTEGER_POSITIVE(String str) { 
    return Regular(str,INTEGER_POSITIVE); 
  }   
  /** 
   *  Determine whether the field is DOUBLE  In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isDouble(String str) { 
    return Regular(str,DOUBLE); 
  } 
  /** 
   *  Determines whether the field is a regular expression for a positive floating point number  >=0  In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isDOUBLE_NEGATIVE(String str) { 
    return Regular(str,DOUBLE_NEGATIVE); 
  } 
  /** 
   *  Determines whether the field is a negative floating point regular expression  <=0  In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isDOUBLE_POSITIVE(String str) { 
    return Regular(str,DOUBLE_POSITIVE); 
  }   
  /** 
   *  Determines whether the field is a date   In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isDate(String str) { 
    return Regular(str,DATE_ALL); 
  } 
  /**
   *  validation 2010-12-10
   * @param str
   * @return
   */
  public static boolean isDate1(String str) { 
    return Regular(str,DATE_FORMAT1); 
  } 
  /** 
   *  Determine if the field is age   In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isAge(String str) { 
    return Regular(str,AGE) ; 
  } 
  /** 
   *  Determine if the field is too long  
   *  The string is returned empty fasle,  More than the length of the {leng} return ture  Conversely return false 
   * @param str 
   * @param leng 
   * @return boolean 
   */
  public static boolean isLengOut(String str,int leng) {    
    return StrisNull(str)?false:str.trim().length() > leng ; 
  } 
  /** 
   *  Determine whether the field is id   In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isIdCard(String str) { 
    if(StrisNull(str)) return false ; 
    if(str.trim().length() == 15 || str.trim().length() == 18) { 
        return Regular(str,IDCARD); 
    }else { 
      return false ; 
    } 
      
  } 
  /** 
   *  Determine whether the field is a zip code   In return ture 
   * @param str 
   * @return boolean 
   */
  public static boolean isCode(String str) { 
    return Regular(str,CODE) ; 
  } 
  /** 
   *  Determines if the string is all English letters  
   * @param str 
   * @return boolean 
   */
  public static boolean isEnglish(String str) { 
    return Regular(str,STR_ENG) ; 
  } 
  /** 
   *  Determines if the string is all English letters + digital  
   * @param str 
   * @return boolean 
   */
  public static boolean isENG_NUM(String str) { 
    return Regular(str,STR_ENG_NUM) ; 
  } 
  /** 
   *  Determines if the string is all English letters + digital + The underline  
   * @param str 
   * @return boolean 
   */
  public static boolean isENG_NUM_(String str) { 
    return Regular(str,STR_ENG_NUM_) ; 
  } 
  /** 
   *  Filter special strings   Returns the filtered string  
   * @param str 
   * @return boolean 
   */
  public static String filterStr(String str) { 
    Pattern p = Pattern.compile(STR_SPECIAL); 
    Matcher m = p.matcher(str); 
    return  m.replaceAll("").trim(); 
  }
   
  /**
   *  Calibration mechanism code format 
   * @return
   */
  public static boolean isJigouCode(String str){
    return Regular(str,JIGOU_CODE) ; 
  }
   
  /** 
   *  Determines whether a string is composed of Numbers  
   * @param str 
   * @return boolean 
   */
  public static boolean isSTR_NUM(String str) { 
    return Regular(str,STR_NUM) ; 
  } 
   
  /** 
   *  Whether the match conforms to a regular expression pattern  Match the return true 
   * @param str  Matched string  
   * @param pattern  Match the pattern  
   * @return boolean 
   */
  private static boolean Regular(String str,String pattern){ 
    if(null == str || str.trim().length()<=0) 
      return false;      
    Pattern p = Pattern.compile(pattern); 
    Matcher m = p.matcher(str); 
    return m.matches(); 
  } 
   
}

Related articles: