1. 程式人生 > >正則表示式大全

正則表示式大全

package org.book.demo.demo;

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

/**
 * Created by ${羅顯} on 2018/9/29
 * 正則表示式驗證工具類
 */
public class RegexUtils {

   final String strWords = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   final char[] charWords = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

    /***
     * 日期正則 支援:
     * YYYY-MM-DD
     * YYYY/MM/DD
     * YYYY_MM_DD
     * YYYYMMDD
     * YYYY.MM.DD的形式
     */
    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)$))";

   final String strLower = "abcdefghijklmnopqrstuvwxyz";
   final String strUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   final String numberWords = "0123456789";
   final String weightWords = "0123456789abcdefghijklmnopqrstuvwxyz0123456789";
    /**
     * 匹配數字組成的字串 ^[0-9]+$
     */
    final String STR_NUM = "^[0-9]+$";
    /**
     * 機構程式碼
     */
    public static final String JIGOU_CODE = "^[A-Z0-9]{8}-[A-Z0-9]$";
    /**
     * 過濾特殊字串正則
     * regEx="[`
[email protected]
#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“'。,、?]"; */ public static final String STR_SPECIAL="[`[email protected]#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“'。,、?]"; /** * 匹配由數字、26個英文字母或者下劃線組成的字串 ^\w+$ */ public static final String STR_ENG_NUM_="^\\w+$"; /** * 身份證正則表示式 */ 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}))"; /** * 匹配由數字和26個英文字母組成的字串 ^[A-Za-z0-9]+$ */ public static final String STR_ENG_NUM="^[A-Za-z0-9]+"; /** * 匹配由26個英文字母組成的字串 ^[A-Za-z]+$ */ public static final String STR_ENG="^[A-Za-z]+$"; /** * 郵編正則表示式 [0-9]\d{5}(?!\d) 國內6位郵編 */ public static final String CODE="[0-9]\\d{5}(?!\\d)"; /** * 年齡正則表示式 ^(?:[1-9][0-9]?|1[01][0-9]|120)$ 匹配0-120歲 */ public static final String AGE="^(?:[1-9][0-9]?|1[01][0-9]|120)$"; /*** * 日期正則 支援: * 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正則表示式 * 匹配 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*)*)$"; //------------------常量定義 /** * 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 = "^([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+)+"; /** * 電話號碼正則表示式= (^(\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}$)" ; /** * 手機號碼正則表示式=^(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正則表示式 ^-?(([1-9]\d*$)|0) */ public static final String INTEGER = "^-?(([1-9]\\d*$)|0)"; /** * 正整數正則表示式 >=0 ^[1-9]\d*|0$ */ public static final String INTEGER_NEGATIVE = "^[1-9]\\d*|0$"; /** * 負整數正則表示式 <=0 ^-[1-9]\d*|0$ */ public static final String INTEGER_POSITIVE = "^-[1-9]\\d*|0$"; /** * Double正則表示式 ^-?([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)$"; /** * 正Double正則表示式 >=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$"; /** * 負Double正則表示式 <= 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$"; /** * [auto 1] * 獲取隨機字串 a-z,A-Z,0-9 * @param length 長度 * @return */ public String autoRandomString(int length) { Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; ++i) { sb.append(strWords.charAt(random.nextInt(62))); } return sb.toString(); } /** * 獲取隨機字串 a-z,A-Z,0-9 作用同[auto 1] * @param length * @return */ public String autoRandomChar(int length) { Random random = new Random(); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < length; i++) { buffer.append(charWords[random.nextInt(62)]); } return buffer.toString(); } /** * 獲取隨機字串 a-z * @param length 長度 * @return */ public String autoLower(int length) { Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; ++i) { sb.append(strLower.charAt(random.nextInt(26))); } return sb.toString(); } /** * 獲取隨機字串 A-Z * @param length 長度 * @return */ public String autoUpper(int length) { Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; ++i) { sb.append(strUpper.charAt(random.nextInt(26))); } return sb.toString(); } /** * 獲取隨機字串 0-9 * @param length 長度 * @return */ public String autoNumber(int length) { Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; ++i) { sb.append(numberWords.charAt(random.nextInt(10))); } return sb.toString(); } /** * 獲取隨機字串 0-9,a-z,0-9 * 有兩遍0-9,增加數字概率 * @param length 長度 * @return */ public String getLowerLetterNumber(int length) { Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; ++i) { sb.append(weightWords.charAt(random.nextInt(46))); } return sb.toString(); } /** * 獲取隨機密碼,lLength位小寫英文+nLength位數字 * @param lLength 字母長度 * @param nLength 數字長度 * @return */ /*public static String getPasswordSimple(int lLength, int nLength) { return autoLower(lLength)+autoNumber(nLength); }*/ /** * 驗證Email * @param email email地址,格式:
[email protected]
[email protected],xxx代表郵件服務商 * @return 驗證成功返回true,驗證失敗返回false */ public static boolean checkEmail(String email) { String regex = "\\[email protected]\\w+\\.[a-z]+(\\.[a-z]+)?"; return Pattern.matches(regex, email); } /** * 驗證身份證號碼 * @param idCard 居民身份證號碼15位或18位,最後一位可能是數字或字母 * @return 驗證成功返回true,驗證失敗返回false */ public static boolean checkIdCard(String idCard) { String regex = "[1-9]\\d{13,16}[a-zA-Z0-9]{1}"; return Pattern.matches(regex,idCard); } /** * 驗證手機號碼(支援國際格式,+86135xxxx...(中國內地),+00852137xxxx...(中國香港)) * @param mobile 移動、聯通、電信運營商的號碼段 *<p>移動的號段:134(0-8)、135、136、137、138、139、147(預計用於TD上網絡卡) *、150、151、152、157(TD專用)、158、159、187(未啟用)、188(TD專用)</p> *<p>聯通的號段:130、131、132、155、156(世界風專用)、185(未啟用)、186(3g)</p> *<p>電信的號段:133、153、180(未啟用)、189</p> * @return 驗證成功返回true,驗證失敗返回false */ public static boolean checkMobile(String mobile) { String regex = "(\\+\\d+)?1[34578]\\d{9}$"; return Pattern.matches(regex,mobile); } /** * 驗證固定電話號碼 * @param phone 電話號碼,格式:國家(地區)電話程式碼 + 區號(城市程式碼) + 電話號碼,如:+8602085588447 * <p><b>國家(地區) 程式碼 :</b>標識電話號碼的國家(地區)的標準國家(地區)程式碼。它包含從 0 到 9 的一位或多位數字, * 數字之後是空格分隔的國家(地區)程式碼。</p> * <p><b>區號(城市程式碼):</b>這可能包含一個或多個從 0 到 9 的數字,地區或城市程式碼放在圓括號—— * 對不使用地區或城市程式碼的國家(地區),則省略該元件。</p> * <p><b>電話號碼:</b>這包含從 0 到 9 的一個或多個數字 </p> * @return 驗證成功返回true,驗證失敗返回false */ public static boolean checkPhone(String phone) { String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$"; return Pattern.matches(regex, phone); } /** * 驗證整數(正整數和負整數) * @param digit 一位或多位0-9之間的整數 * @return 驗證成功返回true,驗證失敗返回false */ public static boolean checkDigit(String digit) { String regex = "\\-?[1-9]\\d+"; return Pattern.matches(regex,digit); } /** * 驗證整數和浮點數(正負整數和正負浮點數) * @param decimals 一位或多位0-9之間的浮點數,如:1.23,233.30 * @return 驗證成功返回true,驗證失敗返回false */ public static boolean checkDecimals(String decimals) { String regex = "\\-?[1-9]\\d+(\\.\\d+)?"; return Pattern.matches(regex,decimals); } /** * 驗證空白字元 * @param blankSpace 空白字元,包括:空格、\t、\n、\r、\f、\x0B * @return 驗證成功返回true,驗證失敗返回false */ public static boolean checkBlankSpace(String blankSpace) { String regex = "\\s+"; return Pattern.matches(regex,blankSpace); } /** * 驗證中文 * @param chinese 中文字元 * @return 驗證成功返回true,驗證失敗返回false */ public static boolean checkChinese(String chinese) { String regex = "^[\u4E00-\u9FA5]+$"; return Pattern.matches(regex,chinese); } /** * 驗證日期(年月日) * @param birthday 日期,格式:1992-09-03,或1992.09.03 * @return 驗證成功返回true,驗證失敗返回false */ /* public static boolean checkDate(String birthday) { String regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}"; return Pattern.matches(regex,birthday); }*/ /** * 驗證URL地址 * @param url 格式:http://blog.csdn.net:80/xyang81/article/details/7705960? 或 http://www.csdn.net:80 * @return 驗證成功返回true,驗證失敗返回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> * 獲取網址 URL 的一級域 * </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); // 獲取完整的域名 //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(); } /** * 匹配中國郵政編碼[6位數字] * @param postcode 郵政編碼 * @return 驗證成功返回true,驗證失敗返回false */ public static boolean checkPostcode(String postcode) { String regex = "[1-9]\\d{5}"; return Pattern.matches(regex, postcode); } /** * 匹配IP地址(簡單匹配,格式,如:192.168.1.1,127.0.0.1,沒有匹配IP段的大小) * @param ipAddress IPv4標準地址 * @return 驗證成功返回true,驗證失敗返回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); } /** * 判斷欄位是否為日期 符合返回ture * @param str * @return boolean */ public boolean isDate(String str) { return Regular(str,DATE_ALL); } /** * 匹配是否符合正則表示式pattern 匹配返回true * @param str 匹配的字串 * @param 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(); } /** * 隨機生成5-6位數字 * @return */ public static int autoNumber(){ int[] array = {0,1,2,3,4,5,6,7,8,9}; Random rand = new Random(); for (int i = 10; i > 1; i--) { int index = rand.nextInt(i); int tmp = array[index]; array[index] = array[i - 1]; array[i - 1] = tmp; } int result = 0; for(int i = 0; i < 6; i++){ result = result * 10 + array[i]; } return result; } /** *隨機生成6位數字 */ public static int autosixNumber(){ //10000 -5位 1000-4位 return (int)((Math.random()*9+1)*100000); } /** * 判斷字串是不是數字組成 * @param str * @return boolean */ public boolean isNumber2(String str) { return Regular(str,STR_NUM) ; } /** * 生成隨機數字和字母 * @param length * @return */ public String getStringRandom(int length) { String val = ""; Random random = new Random(); //length為幾位密碼 for(int i = 0; i < length; i++) { String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; //輸出字母還是數字 if( "char".equalsIgnoreCase(charOrNum) ) { //輸出是大寫字母還是小寫字母 int temp = random.nextInt(2) % 2 == 0 ? 65 : 97; val += (char)(random.nextInt(26) + temp); } else if( "num".equalsIgnoreCase(charOrNum) ) { val += String.valueOf(random.nextInt(10)); } } return val; } /** * 0-9[6位]數字 * @param postcode * @return */ public static boolean checkValidatecode(String postcode) { String regex = "[0-9]\\d{5}"; return Pattern.matches(regex, postcode); } /** * 校驗機構程式碼格式 * @return */ public static boolean isJigouCode(String str){ return Regular(str,JIGOU_CODE) ; } /** * 過濾特殊字串 返回過濾後的字串 * @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(); } /** * 判斷字串是不是全部是英文字母+數字+下劃線 * @param str * @return boolean */ public static boolean isENG_NUM_(String str) { return Regular(str,STR_ENG_NUM_) ; } /** * 判斷欄位是否超長 * 字串為空返回fasle, 超過長度{leng}返回ture 反之返回false * @param str * @param leng * @return boolean */ public static boolean isLengOut(String str,int leng) { return StrisNull(str)?false:str.trim().length() > leng ; } /** * 判斷欄位是否為身份證 符合返回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 ; } } /** * 判斷欄位是否為郵編 符合返回ture * @param str * @return boolean */ public static boolean isCode(String str) { return Regular(str,CODE) ; } /** * 判斷字串是不是全部是英文字母 * @param str * @return boolean */ public static boolean isEnglish(String str) { return Regular(str,STR_ENG) ; } /** * 判斷字串是不是全部是英文字母+數字 * @param str * @return boolean */ public static boolean isENG_NUM(String str) { return Regular(str,STR_ENG_NUM) ; } /** * 判斷欄位是否為空 符合返回ture * @param str * @return boolean */ public static synchronized boolean StrisNull(String str) { return null == str || str.trim().length() <= 0 ? true : false ; } /** * 判斷欄位是非空 符合返回ture * @param str * @return boolean */ public static boolean StrNotNull(String str) { return !StrisNull(str) ; } /** * 判斷欄位是否為年齡 符合返回ture * @param str * @return boolean */ public static boolean isAge(String str) { return Regular(str,AGE) ; } /** * 字串null轉空 * @param str * @return boolean */ public static String nulltoStr(String str) { return StrisNull(str)?"":str; } /** * 字串null賦值預設值 * @param str 目標字串 * @param defaut 預設值 * @return String */ public static String nulltoStr(String str,String defaut) { return StrisNull(str)?defaut:str; } /** * 判斷欄位是否為Email 符合返回ture * @param str * @return boolean */ public static boolean isEmail(String str) { return Regular(str,EMAIL); } /** * 判斷是否為電話號碼 符合返回ture * @param str * @return boolean */ public static boolean isPhone(String str) { return Regular(str,PHONE); } /** * 判斷是否為手機號碼 符合返回ture * @param str * @return boolean */ public static boolean isMobile(String str) { return Regular(str,MOBILE); } /** * 判斷是否為Url 符合返回ture * @param str * @return boolean */ public static boolean isUrl(String str) { return Regular(str,URL); } /** * 判斷欄位是否為數字 正負整數 正負浮點數 符合返回ture * @param str * @return boolean */ public static boolean isNumber(String str) { return Regular(str,DOUBLE); } /** * 判斷欄位是否為INTEGER 符合返回ture * @param str * @return boolean */ public static boolean isInteger(String str) { return Regular(str,INTEGER); } /** * 判斷欄位是否為正整數正則表示式 >=0 符合返回ture * @param str * @return boolean */ public static boolean isINTEGER_NEGATIVE(String str) { return Regular(str,INTEGER_NEGATIVE); } /** * 判斷欄位是否為負整數正則表示式 <=0 符合返回ture * @param str * @return boolean */ public static boolean isINTEGER_POSITIVE(String str) { return Regular(str,INTEGER_POSITIVE); } /** * 判斷欄位是否為DOUBLE 符合返回ture * @param str * @return boolean */ public static boolean isDouble(String str) { return Regular(str,DOUBLE); } /** * 判斷欄位是否為正浮點數正則表示式 >=0 符合返回ture * @param str * @return boolean */ public static boolean isDOUBLE_NEGATIVE(String str) { return Regular(str,DOUBLE_NEGATIVE); } /** * 判斷欄位是否為負浮點數正則表示式 <=0 符合返回ture * @param str * @return boolean */ public static boolean isDOUBLE_POSITIVE(String str) { return Regular(str,DOUBLE_POSITIVE); } /** * 驗證2010-12-10 * @param str * @return */ public static boolean isDate1(String str) { return Regular(str,DATE_FORMAT1); } }