標籤:chm his ESS final .com fonts IV 編輯 第一個
Java Regex
Regex定義了字串的模式。
Regex可以用來搜尋、編輯或處理文本。
Regex並不僅限於某一種語言,但是在每種語言中有細微的差別。
Regex執行個體
一個字串其實就是一個簡單的Regex,例如 Hello World Regex匹配 "Hello World" 字串。
.(點號)也是一個Regex,它匹配任何一個字元如:"a" 或 "1"。
下表列出了一些Regex的執行個體及描述:
| Regex |
描述 |
this is text |
匹配字串 "this is text" |
this\s+is\s+text |
注意字串中的 \s+。 匹配單詞 "this" 後面的 \s+ 可以匹配多個空格,之後匹配 is 字串,再之後 \s+ 匹配多個空格然後再跟上 text 字串。 可以匹配這個執行個體:this is text |
^\d+(\.\d+)? |
^ 定義了以什麼開始 \d+ 匹配一個或多個數字 ? 設定括弧內的選項是可選的 \. 匹配 "." 可以匹配的執行個體:"5", "1.5" 和 "2.21"。 |
Java Regex和 Perl 的是最為相似的。
java.util.regex 包主要包括以下三個類:
- Pattern 類:
pattern 對象是一個Regex的編譯表示。Pattern 類沒有公用構造方法。要建立一個 Pattern 對象,你必須首先調用其公用靜態編譯方法,它返回一個 Pattern 對象。該方法接受一個Regex作為它的第一個參數。
- Matcher 類:
Matcher 對象是對輸入字串進行解釋和匹配操作的引擎。與Pattern 類一樣,Matcher 也沒有公用構造方法。你需要調用 Pattern 對象的 matcher 方法來獲得一個 Matcher 對象。
- PatternSyntaxException:
PatternSyntaxException 是一個非強制異常類,它表示一個Regex模式中的語法錯誤。
/** * 擷取當前的httpSession * @author :shijing * 2016年12月5日下午3:46:02 * @return */ public static HttpSession getSession() { return getRequest().getSession(); } /** * 手機號驗證 * @author :shijing * 2016年12月5日下午4:34:46 * @param str * @return 驗證通過返回true */ public static boolean isMobile(final String str) { Pattern p = null; Matcher m = null; boolean b = false; p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 驗證手機號 m = p.matcher(str); b = m.matches(); return b; } /** * 電話號碼驗證 * @author :shijing * 2016年12月5日下午4:34:21 * @param str * @return 驗證通過返回true */ public static boolean isPhone(final String str) { Pattern p1 = null, p2 = null; Matcher m = null; boolean b = false; p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 驗證帶區號的 p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$"); // 驗證沒有區號的 if (str.length() > 9) { m = p1.matcher(str); b = m.matches(); } else { m = p2.matcher(str); b = m.matches(); } return b; } public static void main(String[] args) { String phone = "13900442200"; String phone2 = "021-88889999"; String phone3 = "88889999"; String phone4 = "1111111111"; //測試1 if(isPhone(phone) || isMobile(phone)){ System.out.println("1這是符合的"); } //測試2 if(isPhone(phone2) || isMobile(phone2)){ System.out.println("2這是符合的"); } //測試3 if(isPhone(phone3) || isMobile(phone3)){ System.out.println("3這是符合的"); } //測試4 if(isPhone(phone4) || isMobile(phone4)){ System.out.println("4這是符合的"); }else{ System.out.println("不符合"); } }
如有疑問,歡迎關注公眾號“業餘草”!
業餘草 JavaRegex,驗證手機號和電話號碼