Java 正則表達式學習筆記

常用收集

/**
 * 正則工具類
 */
public class RegexUtil {
	/**
	 * 匹配圖象
	 * 格式: /相對路徑/文件名.後綴 (後綴爲gif,dmp,png)
	 * 匹配 : /forum/head_icon/admini2005111_ff.gif 或 admini2005111.dmp
	 * 不匹配: c:/admins4512.gif
	 */
	public static final String ICON_REGEXP = "^(/{0,1}//w){1,}//.(gif|dmp|png|jpg)$|^//w{1,}//.(gif|dmp|png|jpg)$";

	/**
	 * 匹配email地址
	 * 格式: [email protected]
	 * 匹配 : [email protected][email protected]
	 * 不匹配: foo@bar 或 [email protected]
	 */
	public static final String EMAIL_REGEXP = "(?://w[-._//w]*//w@//w[-._//w]*//w//.//w{2,3}$)";

	/**
	 * 匹配並提取url
	 * 格式: XXXX://XXX.XXX.XXX.XX/XXX.XXX?XXX=XXX
	 * 匹配 : http://www.suncer.com 或news://www
	 * 不匹配: c:/window
	 */
	public static final String URL_REGEXP = "(//w+)://([^/:]+)(://d*)?([^#//s]*)";

	/**
	 * 匹配並提取http
	 * 格式: http://XXX.XXX.XXX.XX/XXX.XXX?XXX=XXX 或 ftp://XXX.XXX.XXX 或
	 * https://XXX
	 * 匹配 : http://www.suncer.com:8080/index.html?login=true
	 * 不匹配: news://www
	 */
	public static final String HTTP_REGEXP = "(http|https|ftp)://([^/:]+)(://d*)?([^#//s]*)";

	/**
	 * 匹配日期
	 * 格式(首位不爲0): XXXX-XX-XX或 XXXX-X-X
	 * 範圍:1900--2099
	 * 匹配 : 2005-04-04
	 * 不匹配: 01-01-01
	 */
	public static final String DATE_BARS_REGEXP = "^((((19){1}|(20){1})\\d{2})|\\d{2})-[0,1]?\\d{1}-[0-3]?\\d{1}$";

	/**
	 * 匹配日期
	 * 格式: XXXX/XX/XX
	 * 範圍:
	 * 匹配 : 2005/04/04
	 * 不匹配: 01/01/01
	 * 
	 */
	public static final String DATE_SLASH_REGEXP = "^[0-9]{4}/(((0[13578]|(10|12))/(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)/(0[1-9]|[1-2][0-9]|30)))$";

	/**
	 * 匹配電話
	 * 格式爲: 0XXX-XXXXXX(10-13位首位必須爲0) 或0XXX XXXXXXX(10-13位首位必須爲0) 或
	 * 		(0XXX)XXXXXXXX(11-14位首位必須爲0) 或 XXXXXXXX(6-8位首位不爲0) 或
	 * 		XXXXXXXXXXX(11位首位不爲0)
	 * 匹配 : 0371-123456 或 (0371)1234567 或 (0371)12345678 或 010-123456 或
	 * 010-12345678 或 12345678912
	 * 不匹配: 1111-134355 或 0123456789
	 * 
	 */
	public static final String PHONE_REGEXP = "^(?:0[0-9]{2,3}[-//s]{1}|//(0[0-9]{2,4}//))[0-9]{6,8}$|^[1-9]{1}[0-9]{5,7}$|^[1-9]{1}[0-9]{10}$";

	/**
	 * 匹配身份證
	 * 格式爲: XXXXXXXXXX(10位) 或 XXXXXXXXXXXXX(13位) 或 XXXXXXXXXXXXXXX(15位) 或 * XXXXXXXXXXXXXXXXXX(18位)
	 * 匹配 : 0123456789123
	 * 不匹配: 0123456
	 */
	public static final String ID_CARD_REGEXP = "^//d{10}|//d{13}|//d{15}|//d{18}$";

	/**
	 * 匹配郵編代碼
	 * 格式爲: XXXXXX(6位)
	 * 匹配 : 012345
	 * 不匹配: 0123456
	 * 
	 */
	public static final String ZIP_REGEXP = "^[0-9]{6}$";// 匹配郵編代碼

	/**
	 * 不包括特殊字符的匹配 (字符串中不包括符號 數學次方號^ 單引號' 雙引號" 分號; 逗號, 帽號: 數學減號- 右尖括號> 左尖括號< 反斜槓/ * 即空格,製表符,回車符等 )
	 * 格式爲: x 或 一個一上的字符
	 * 匹配 : 012345
	 * 不匹配: 0123456 // ;,:-<>//s].+$";//
	 */
	public static final String NON_SPECIAL_CHAR_REGEXP = "^[^'/";
	
	// 匹配郵編代碼
	/**
	 * 匹配非負整數(正整數 + 0)
	 */
	public static final String NON_NEGATIVE_INTEGERS_REGEXP = "^//d+$";

	/**
	 * 匹配不包括零的非負整數(正整數 > 0)
	 */
	public static final String NON_ZERO_NEGATIVE_INTEGERS_REGEXP = "^[1-9]+//d*$";

	/**
	 * 匹配正整數
	 */
	public static final String POSITIVE_INTEGER_REGEXP = "^[0-9]*[1-9][0-9]*$";

	/**
	 * 匹配非正整數(負整數 + 0)
	 */
	public static final String NON_POSITIVE_INTEGERS_REGEXP = "^((-//d+)|(0+))$";

	/**
	 * 匹配負整數
	 */
	public static final String NEGATIVE_INTEGERS_REGEXP = "^-[0-9]*[1-9][0-9]*$";

	/**
	 * 匹配整數
	 */
	public static final String INTEGER_REGEXP = "^-?//d+$";

	/**
	 * 匹配非負浮點數(正浮點數 + 0)
	 */
	public static final String NON_NEGATIVE_RATIONAL_NUMBERS_REGEXP = "^//d+(//.//d+)?$";

	/**
	 * 匹配正浮點數
	 */
	public static final String POSITIVE_RATIONAL_NUMBERS_REGEXP = "^(([0-9]+//.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*//.[0-9]+)|([0-9]*[1-9][0-9]*))$";

	/**
	 * 匹配非正浮點數(負浮點數 + 0)
	 */
	public static final String NON_POSITIVE_RATIONAL_NUMBERS_REGEXP = "^((-//d+(//.//d+)?)|(0+(//.0+)?))$";

	/**
	 * 匹配負浮點數
	 */
	public static final String NEGATIVE_RATIONAL_NUMBERS_REGEXP = "^(-(([0-9]+//.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*//.[0-9]+)|([0-9]*[1-9][0-9]*)))$";

	/**
	 * 匹配浮點數
	 */
	public static final String RATIONAL_NUMBERS_REGEXP = "^(-?//d+)(//.//d+)?$";

	/**
	 * 匹配由26個英文字母組成的字符串
	 */
	public static final String LETTER_REGEXP = "^[A-Za-z]+$";

	/**
	 * 匹配由26個英文字母的大寫組成的字符串
	 */
	public static final String UPWARD_LETTER_REGEXP = "^[A-Z]+$";

	/**
	 * 匹配由26個英文字母的小寫組成的字符串
	 */
	public static final String LOWER_LETTER_REGEXP = "^[a-z]+$";

	/**
	 * 匹配由數字和26個英文字母組成的字符串
	 */
	public static final String LETTER_NUMBER_REGEXP = "^[A-Za-z0-9]+$";

	/**
	 * 匹配由數字、26個英文字母或者下劃線組成的字符串
	 */
	public static final String LETTER_NUMBER_UNDERLINE_REGEXP = "^//w+$";
	
	/**
	 * 協議 
	 * "http://blog.csdn.net/jx520"
	 * 獲得:http://
	 */
	public static final String PROTOCOL_NAME_REGEXP = "((http|ftp|https)://)";
	
	/**
	 * 域名 
	 * "http://blog.csdn.net/jx520"
	 * 獲得:csdn.net
	 */
	public static final String DOMAIN_NAME_REGEXP = "(?<=http://|https://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|shop|club|vip|tv|top|site)";
	
	/**
	 * 完整域名 
	 * "http://blog.csdn.net/jx520"
	 * 獲得:blog.csdn.net
	 */
	public static final String FULL_DOMAIN_NAME_REGEXP = "[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)";

	//--------------------------------- 方法 ---------------------------------------------
	/**
	 * 正規表達式批配
	 * @param source 批配的源字符串
	 * @param regexp 批配的正規表達式
	 * @param caseType 是否大小寫敏感 
	 * @return 如果源字符串符合要求返回真,否則返回假
	 */
	public static boolean isValidate(String source, String regexp, int caseType) {
		if(source == null || regexp == null){
			return false;
		}
		try {
			// 實例正規表達式模板
			Pattern p = Pattern.compile(regexp, caseType);
			Matcher matcher = p.matcher(source);
			matcher.find();
			// 返回批配結果
			return !"".equals(matcher.group().trim()); // 返回文本字符串
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 大小寫【敏感】的正規表達式批配
	 * @param source 批配的源字符串
	 * @param regexp 批配的正規表達式
	 * @return 如果源字符串符合要求返回真,否則返回假
	 */
	public static boolean isValidate(String source, String regexp) {
		if(source == null || regexp == null){
			return false;
		}
		try {
			// 實例大小寫敏感的正規表達式模板
			Pattern p = Pattern.compile(regexp);
			Matcher matcher = p.matcher(source);
			matcher.find();
			// 返回批配結果
			return !"".equals(matcher.group().trim()); // 返回布爾值
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 獲取匹配的字符串
	 * @param source 批配的源字符串
	 * @param regexp 批配的正規表達式
	 * @return 如果找到,返回符合要求字符串,否則返回 ""
	 */
	public static String getByRegex(String source, String regexp) {
		if(source == null || regexp == null){
			return "";
		}
		StringBuilder sb = new StringBuilder();
		try {
			// 實例大小寫敏感的正規表達式模板
			Pattern p = Pattern.compile(regexp);
			Matcher matcher = p.matcher(source);
			while (matcher.find()) {
				sb.append(matcher.group().trim());
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}
		return sb.toString();
	}
	
	/**
	 * 獲取匹配的字符串
	 * @param source 批配的源字符串
	 * @param regexp 批配的正規表達式
	 * @param target 批配內容將被替換成此字符串
	 * @return 將所有找到的字符替換成目標字符串,返回替換後的字符串
	 * 
	 */
	public static String replaceAll(String source, String regexp, String target) {
		if(source == null || regexp == null || target == null){
			return "";
		}
		try {
			// 實例大小寫敏感的正規表達式模板
			Pattern p = Pattern.compile(regexp);
			Matcher matcher = p.matcher(source);
			matcher.find();
			return matcher.replaceAll(target).trim();//將所有找到的字符替換成目標字符串
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}
	}
	
	//----------------------------- 具體功能 -------------------------------
	/**
	 * 從 URL 中取出協議名。"http://blog.csdn.net/jx520" 獲得:http://
	 * @param url
	 * @return
	 */
	public static String getProtocolName(String url) {
		return getByRegex(url, PROTOCOL_NAME_REGEXP);
	}
	
	/**
	 * 從 URL 中取出根域名。"http://blog.csdn.net/jx520" 獲得:csdn.net
	 * @param url
	 * @return
	 */
	public static String getDomainName(String url) {
		return getByRegex(url, DOMAIN_NAME_REGEXP);
	}

	/**
	 * 從 URL 中取出完整域名。"http://blog.csdn.net/jx520" 獲得:blog.csdn.net
	 * @param url
	 * @return
	 */
	public static String getFullDomainName(String url) {
		return getByRegex(url, FULL_DOMAIN_NAME_REGEXP);
	}
	
	/**
	 * 過濾掉特殊字符串,只保存  大小寫字母、數字、中文、常用符號
	 * @param url
	 * @return
	 */
	public static String clearIllegalCharacters(String str) {
		return getByRegex(str, "([A-Za-z_\\d\\u4E00-\\u9FA5\"\\-\\\\\\/\\.\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\+\\=\\|\\{\\}\\'\\:\\;\\'\\,\\[\\]\\.\\<\\>\\/\\?\\~\\!\\@\\#\\¥\\%\\…\\&\\*\\(\\)\\—\\—\\+\\|\\{\\}\\【\\】\\‘\\;\\:\\”\\“\\’\\。\\,\\、\\?])+");
	}
	
	/**
	 * 過濾掉特殊字符串,只保存  大小寫字母、數字、中文、常用符號 (包含空格)
	 * @param url
	 * @return
	 */
	public static String clearIllegalCharactersWithSpace(String str) {
		return getByRegex(str, "([A-Za-z_\\d\\s\\u4E00-\\u9FA5\"\\-\\\\\\/\\.\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\+\\=\\|\\{\\}\\'\\:\\;\\'\\,\\[\\]\\.\\<\\>\\/\\?\\~\\!\\@\\#\\¥\\%\\…\\&\\*\\(\\)\\—\\—\\+\\|\\{\\}\\【\\】\\‘\\;\\:\\”\\“\\’\\。\\,\\、\\?])+");
	}

	public static void main(String[] args) {
		System.out.println("域名 vaeasefavfasfe.csdn.net/jx520 是:" + getDomainName("vaeasefavfasfe.csdn.net/jx520"));
		System.out.println("域名是:" + getDomainName("http://csdn.net/jx520"));
		System.out.println("域名是:" + getDomainName("https://csdn.net/jx520"));
		System.out.println("域名是:" + getDomainName("http://blog.csdn.net/jx520"));
		System.out.println("域名是:" + getDomainName("https://blog.csdn.net/jx520"));
	}
}

參考資料

Java 正則表達式
https://www.javatpoint.com/java-regex
https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章