注意:正則表達式只關注格式是否正確,不關注內容是否有效。
一、字符集合, []表示一個字符。
1、[abc] :指a,b,c中的任意一個字符。
2、[^abc]:指除了a,b,c外的任意字符。
3、[a-z]:表示a到z間的任意一個字符。
4、[a-zA-Z0-9]:表示a到z,A到Z,0到9的任意一個字符。
5、[a-z&&[^bc]]:等價於[ad-z],指a到z間除了b,c字符的任意字符。
二、預定義字符集* ( . )表示任意一個字符。
1、\d : 數字字符集,相當於[0-9],
2、\w:單詞字符集,相當於[a-zA-Z0-9_]。
3、\s:空白字符集,相當於[\t\n\f\r\xoB]。
4、\D:非\d
5、\W:非\w
6、\S:非\s
三、數量詞
1、?表示0個或一個。
2、* 表示0個或無窮個。
3、+ 表示1個或無窮個。
4、{n}表示n個。
5、{n, }表示n個到無窮個。
6、{n, m }表示n個到m個(m>n)。
7、() 表示一個整體。比如:(\+86)就是表示+86,此時+需要轉義。
8、^在[]中表示非,而放在[]外,表示以……開頭。比如^[0-9]就是以數字0-9開頭。
9、$表示以……結尾,比如[0-9]$就是指以數字0-9結尾。
四、java的String中正則表達式寫法(轉義的問題)
1、11位手機號正則表達式: "^[0-9]{11}$" ;
2、郵箱正則表達式:"^[a-zA-Z0-9_]+@[a-zA-Z0-9_]+(\.[a-zA-Z0-9])+$" ;此時若使用String regex = " [a-zA-Z0-9_]+@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9])+ "; 由於java字符串認為 ( . ) 不需要進行轉義,所以寫成 ( \. )會報錯,需要對 \ 進行轉義, 即寫成 ( \\. )
3、簡單的日期表達式:"^\\d{4}(\\-|\\/|\\.)\\d{1,2}\\1\\d{1,2}$" ; \1表示匹配第一個小括號的內容,即(\-|\/|\.)
1 public class Test { 2 public static void main(String[] args) { 3 String regexDemo1 = "^\\d{4}(\\-|\\/|\\.)\\d{1,2}\\1\\d{1,2}$"; 4 String str = "2019.05.22"; 5 System.out.println(str.matches(regexDemo1)); // 返回true 6 7 // regexDemo1等價於regexDemo2。 其 \1 指的即為第一個小括號(), 即 \1 指的是 (\-|\/|\.) 8 String regexDemo2 = "^\\d{4}(\\-|\\/|\\.)\\d{1,2}(\\-|\\/|\\.)\\d{1,2}$"; 9 System.out.println(str.matches(regexDemo2)); // 返回true 10 } 11 }
五、字符串的替換與分解(使用正則表達式)
1、public boolean matches(String regex);判斷當前字符串對象是否與參數regex格式相匹配。
2、public String replaceAll(String regex, String replacement);將字符串中符合regex格式的子串替換成replacement,此時並未改變原始字符串。
3、public String[] split(String regex); 將字符串使用regex標記分割,並將分割后的單詞存入字符串數組中。
1 public class Test { 2 public static void main(String[] args) { 3 String regex = "[0-9]+"; 4 String str = "hello123world123"; 5 System.out.println("原始字符串為: " + str);//輸出hello123world123 6 7 System.out.println("替換字符串后為: " +str.replaceAll(regex, " welcome ")); //輸出hello welcome world welcome 8 System.out.println("原字符串不變:" + str); //不會改變原來的字符串,輸出為hello123world123 9 10 System.out.println("輸出切割后的字符串: "); 11 String digitWord[] = str.split(regex); // 以regex格式分割 12 for (String s : digitWord) { 13 System.out.println(s); 14 } 15 } 16 } 17 /* 18 測試結果為: 19 原始字符串為: hello123world123 20 替換字符串后為: hello welcome world welcome 21 原字符串不變:hello123world123 22 輸出切割后的字符串: 23 hello 24 world 25 */