(一)正則表達式及語法簡介
- String類使用正則表達式的幾個方法:
- 正則表達式支持的合法字符:
- 特殊字符:
- 預定義字符:
- 方括號表達式:
- 圓括號表達式:用於將多個表達式組成一個子表達式,可以使用或運算符“|”,比如正則表達式:"(aa|bb|cc)"就表示匹配"aa"、"bb"、"cc"三個字符串中的其中一個。
- 邊界匹配符:
- 貪婪、勉強、占有模式的數量標識符:
(二)Java正則表達式的簡單用法
- 兩個關鍵類:(1)Pattern:正則表達式編譯后在內存中的表示形式。是不可變類,可供多個線程並發使用;(2)Matcher:保存執行匹配所涉及的各種狀態,多個Matcher對象可以共享一個Pattern對象。
- 簡單用法程序示例:
1 System.out.println(Pattern.matches("a\\wb", "a_b")); // 輸出:true 2 Pattern p = Pattern.compile("a*b"); 3 Matcher m = p.matcher("aabzaaadaaafbc"); 4 System.out.println(m.matches()); // 輸出:false
-
Matcher類的常用方法:
- 程序舉例:
1 public static void test1() { 2 System.out.println(Pattern.matches("a\\wb", "a_b")); // 輸出:true 3 4 Pattern p = Pattern.compile("a*b"); 5 Matcher m = p.matcher("aabzaaadaaafbc"); 6 7 System.out.println(m.matches()); // 輸出:false 8 System.out.println(m.find()); // 輸出:true 9 System.out.println(m.group()); // 輸出:b 10 System.out.println(m.start()); // 輸出:2 11 System.out.println(m.end()); // 輸出:3 12 System.out.println(m.lookingAt()); // 輸出:true 13 m.reset("zab"); 14 System.out.println(m.lookingAt()); // 輸出:false 15 } 16 17 public static void test2() { 18 Matcher m = Pattern.compile("\\w+").matcher("Java is very easy!"); 19 20 while (m.find()) { 21 System.out.println(m.group() + "子串的起始位置:" + m.start() + ",結束位置:" 22 + m.end()); 23 } 24 25 int i = 0; 26 while (m.find(i)) { 27 System.out.print(m.group() + "\t"); 28 i++; 29 } 30 31 // 輸出: 32 // Java子串的起始位置:0,結束位置:4 33 // is子串的起始位置:5,結束位置:7 34 // very子串的起始位置:8,結束位置:12 35 // easy子串的起始位置:13,結束位置:17 36 // Java ava va a is is s very very ery ry y easy easy asy sy y 37 } 38 39 public static void test3() { 40 String[] mails = { "Jiayongji@163.com", "Jiayongji@gmail.com", 41 "jy@hust.org", "wawa@abc.cc" }; 42 String mailRegEx = "\\w{3,20}@\\w+\\.(com|cn|edu|org|net|gov)"; 43 Pattern mailPattern = Pattern.compile(mailRegEx); 44 45 Matcher mailMatcher = null; 46 47 for (String mail : mails) { 48 if (mailMatcher == null) { 49 mailMatcher = mailPattern.matcher(mail); 50 } else { 51 mailMatcher.reset(mail); 52 } 53 54 System.out.println(mail + (mailMatcher.matches() ? "是" : "不是") 55 + "一個合法的郵箱地址"); 56 } 57 58 // 輸出: 59 // Jiayongji@163.com是一個合法的郵箱地址 60 // Jiayongji@gmail.com是一個合法的郵箱地址 61 // jy@hust.org不是一個合法的郵箱地址 62 // wawa@abc.cc不是一個合法的郵箱地址 63 64 } 65 66 public static void test4() { 67 Matcher m = Pattern.compile("\\bre\\w*").matcher( 68 "Java is real good at inrestart and regex."); 69 System.out.println(m.replaceAll("哈哈")); 70 71 // 輸出: 72 // Java is 哈哈 good at inrestart and 哈哈. 73 74 }
Refer:《瘋狂Java講義(第二版)》
(完)