Pattern類和Matcher類
概述:
Pattern類屬於java.util.regex包中的一個類。
java.util.regex.Pattern;
public final class Pattern
extends Object
implements Serializable
Matcher類也是屬於java.util.regex包中的一個類。
java.util.regex.Matcher;
public final class Matcher
extneds Object
implements MatchResult
Pattern和Matcher配合使用:
模式和匹配器的典型調用順序:
Pattern p=Pattern.compile(“a*b”);
Matcher m=p.matcher(“aaaaaaab”);
boolean b=m.matches();
下面看一段代碼來具體解釋模式和匹配器的典型調用順序:
package 正則表達式;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo8_Pattern {
public static void main(String[] args) {
// Pattern和Matcher的結合使用
//模式和匹配器典型的調用順序
Pattern p=Pattern.compile("a*b"); //獲取到正則表達式
Matcher m=p.matcher("aaaaaab"); //獲取匹配器
boolean b=m.matches(); //看是否能匹配,匹配就返回true
System.out.println(b); //true
System.out.println("aaaaaab".matches("a*b")); //完成了上述功能,與上面結果一樣true
}
}
正則表達式的獲取功能
Matcher類中的boolean find()方法:嘗試查找與該模式匹配的輸入序列的下一個子序列。String group():返回由以前匹配操作所匹配的輸入子序列。
下面看一段代碼示例:
package 正則表達式;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo8_Pattern {
public static void main(String[] args) {
// Pattern和Matcher的結合使用
//需求:把一個字符串中的手機號碼獲取出來
String s="我的手機號碼是18988888888,我以前的手機號是19923333333,我還有一個手機號是18899898988";
String regex="1[35789]\\d{9}";
Pattern p=Pattern.compile(regex); //獲取到正則表達式
Matcher m=p.matcher(s); //獲取匹配器
//獲取一個手機號碼
boolean b1=m.find();
System.out.println(b1); //true
String s1=m.group(); //要獲取查找到的字符串,必須先獲取即使用find()方法,否則,報錯
System.out.println(s1); //18988888888
/*
獲取字符串中所有的手機號碼
18988888888
19923333333
18899898988
*/
while(m.find()) {
System.out.println(m.group());
}
}