標籤:eal 編程 運算式 並集 font greedy 擷取的群組 字元 ring
1, [abc] a, b 或 c
[^abc] 任何字元,除了a,b 或 c
[a-zA-Z] a 到 z 或 A 到 Z,兩頭字元都包括在內
[a-d[m-p]] a 到 d 或 m 到 p :[a-dm-p](並集)
[a-z&&[def]] d,e 或 f(交集)
2, * 任何字元
\d 數字: [0-9]
\D 非數字:[^0-9]
\s 空白字元:[\t\n\x0B\f\r]
\S 非空白字元:[^\s]
\w 單詞字元:[a-zA-Z_0-9]
\W 非單詞字元:[^\w]
3, Greedy 數量詞
X? 一次或一次也沒有
X* 零次或多次
X+ 一次或多次
X{n} 恰好n次
X{n,} 至少n次
X{n,m} 至少n次,但是不超過m次字串
4, 替換功能
String s = "Hello123World";
String regex = "\\d";
String s2 = s.replaceAll(regex, "");
5, 分組功能
擷取的群組可以通過從左至右計算其開括弧來編號,((A)(B(C)))存在4個這樣的組
1 ((A)(B(C)))
2 (A)
3 (B(C))
4 (C)
應用:疊詞切割:"sdqqfgkkkhjppppkl";
String regex = "(.)\\1+"; String[] arr = s.split(regex);
應用:把字串"我我....我...我.我...要要...要學....學學..學.編.編編.編.程...程程...程"輸出為"我要學編程"
String s = "我我....我...我.我...要要...要學....學學..學.編.編編.編.程...程程...程";
String s2 = s.replaceAll("\\.+", "");
String s3 = s2.replaceAll("(.)\\1+", "$1");
6, Pattern和Matcher
Pattern p = Pattern.compile(a*b); //擷取到Regex
Matcher m = p.matcher("aaaaaab"); //擷取匹配器
boolean b = m.matches(); //看是否能匹配,匹配就返回true
等價於System.out.println("aaaaaab".matches("a*b"));
應用:擷取字串中的電話號碼
String s = "我的電話號碼是18988888888,曾經用過18987654321,還用過18812345678";
String regex = "1[3578]\\d{9}";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
while(m.find()) System.out.println(m.group()); //必須先find再group
javaRegex