一、Java Matcher對象中find()與matches()的區(qū)別
find():是否存在與該模式匹配的下一個子序列。簡單來說就是在字符某部分匹配上模式就會返回true,同時匹配位置會記錄到當(dāng)前位置,再次調(diào)用時從該處匹配下一個。
matches():整個字符串是否匹配上模式,匹配上則返回true,否則false。
@Test
public void patternTest() {
??? String str = “hellohellohello”;
??? String regex = “hello”;
??? Pattern pattern = Pattern.compile(regex);
??? Matcher matcher = pattern.matcher(str);
??? System.out.println(matcher.find());
??? System.out.println(matcher.matches());
}
輸出結(jié)果為:
find() -> true
matches() -> false
再拓展兩個函數(shù),Matcher中的start()和end()。start(),點進(jìn)方法可以看到返回的是上一個匹配項的起始索引,如果沒有匹配項將拋出IllegalStateException異常。同理,end()則為結(jié)束的索引。
好了,那我們來看一個例子:
@Test
public void patternTest() {
??? String str = “hellohellohello”;
??? String regex = “hello”;
??? Pattern pattern = Pattern.compile(regex);
??? Matcher matcher = pattern.matcher(str);
??? while (matcher.find()) {
????? System.out.println(matcher.start() + “->” + matcher.end());
??? }
}
輸出:
0->5
5->10
10->15
可以看出find()匹配完后會記錄當(dāng)前匹配位置知道最后。
我們再看看另外一種情況,嘗試在matcher.matches()后面再匹配一次matcher.find()會發(fā)生什么情況?
@Test
public void patternTest() {
??? String str = “hello”;
??? String regex = “hello”;
??? Pattern pattern = Pattern.compile(regex);
??? Matcher matcher = pattern.matcher(str);
??????? System.out.println(“find() -> ” + matcher.find());
??? System.out.println(“matches() -> ” + matcher.matches());
??? System.out.println(“find() -> ” + matcher.find());
}
輸出結(jié)果為:
find() -> true
matches() -> true
find() -> false
matcher.find()名列前茅次為true,第二次卻為false,這將帶來了好多小問號了。我們還是進(jìn)入matches()方法看看,從this.oldLast = this.last可以看出,matches()更新了最后匹配位置,所以在使用find()去找下一個匹配位置時,就找不到了,所以為false。而如果要重置匹配位置,可以使用find(0)(說明:find(int start),重置匹配器,然后嘗試查找索引start開始的下一個滿足匹配的子序列,所以find(0)相當(dāng)于重置為最原始狀態(tài))。
延伸閱讀:
二、什么是Java
Java是一門面向?qū)ο缶幊陶Z言,不僅吸收了C++語言的各種優(yōu)點,還摒棄了C++里難以理解的多繼承、指針等概念,因此Java語言具有功能強(qiáng)大和簡單易用兩個特征。Java語言作為靜態(tài)面向?qū)ο缶幊陶Z言的代表,極好地實現(xiàn)了面向?qū)ο罄碚?,允許程序員以優(yōu)雅的思維方式進(jìn)行復(fù)雜的編程 。