正則表示式Pattern類和Matcher類
正則表示式:本質是一個字串,用來定義匹配規則的。
字元x 代表的是字元x
\\ 代表的是反斜線\
\t 製表符
\n 換行符
\r 回車符
[abc] 代表的是字元a、b或c
[^abc] 代表的是除a b c 以外的任何字元
[a-zA-Z] 代表的是a到z或A到Z
[0-9] 代表的是0-9數字
[a-zA-Z_0-9] 代表的是字母或數字或下劃線
. 代表任何字元
\d 代表0-9數字
\w 代表字母數字下劃線
x? 代表的是x出現一次或一次都沒有
x* 零次或多次
x+ 一次或多次
x{n} 恰好n次
x{n,} 至少n次
x{n,m} 至少n次但不超過m次
Pattern類:作用是編譯正則表示式後建立一個匹配模式
方法:
Pattern compile(String regex) 由於Pattern類的建構函式是私有的,不可以直接建立,所以通過靜態方法compile(String regex)方法來建立,將給定的正則表示式編譯並賦予給Pattern類
Matcher matcher(String str) 對指定的字串建立一個Matcher物件
boolean matches() 對輸入的字串進行匹配檢測,也就是整個字串完全匹配才返回真值。
一個小Demo
public class PatternDemo {
public static void main(String[] args) {
String pattern = "[?|*]";
Pattern p = Pattern.compile(pattern);
System.out.println(p.pattern());
String str ="*";
Matcher m = p.matcher(str);
System.out.println(m.matches());
}
}
字串類中涉及正則表示式的常用方法
boolean matches(String regex) 匹配成功返回true
String[] split(String regex) 使用規則將字串分割
String replaceAll(String regex,String str) 按照規則替換字串
public class RegexDemo {
public static void main(String[] args) {
//字串中涉及正則表示式的方法
String regex = "a*b";
String s = "aaab";
boolean flag = s.matches(regex);
System.out.println(flag);
String s1 ="ab.ba.baab";
String regex1 ="\\.";
String[] splitStr = s1.split(regex1);
for(int i=0;i<splitStr.length;i++){
System.out.println("第"+(i+1)+"個是:"+splitStr[i]);
}
String s2 = s1.replaceAll(regex1, "cc");
System.out.println(s2);
}
}