徒弟:前面幾節課跟師傅學習了字元組,括号的作用,還有什麼呢?
師傅:還有好多呀,例如錨點!
問題引出:
public class GeneralOne {
public static void main(String[] args) {
String str = "This sentence contains word cat";
String regex = "cat";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
if(m.find()){
System.out.println("找到 cat !");
}else{
System.out.println("沒有找到 cat !");
}
運作結果:
找到 cat !
判斷句子中是否存在cat的單詞。
那麼我們查找的是cat這個子字元串,還是cat這個單詞
為了驗證這一點,我們在t後面加個e
String str = "This sentence contains word cate";
奇怪,程式報告找到cat,而句子中是不包含單詞cat的。說明隻能比對字元串cat,而不能比對單詞cat
再試試:
String regex = "\\scat\\s";
要求cat兩端出現空白字元,運作結果:
沒有找到 cat !
此時,正确發現不包含單詞cat
如果是這樣呢?
按道理,應該是包含的,隻是在末尾沒有空格!
如果這樣子呢:
String str = "This sentence contains word 'cat'";
當然,實際情況,可能會更加複雜,需要一種辦法解決:錨點
錨點
l 作用:規定比對的位置
l 形式:\b 單詞分界符錨點
規定在反斜線的一側必須出現的單詞,另一側不可以出現單詞字元。
例子:
public class GeneralTwo {
String[] strings = {"This sentence contains word cat","This sentence contains word 'cat'","This sentence contains word vacation","This sentence contains word \"cate\""};
String regex = "\\bcat\\b";
for(String str:strings){
System.out.println("處理句子:"+str);
處理句子:This sentence contains word cat
處理句子:This sentence contains word 'cat'
處理句子:This sentence contains word vacation
處理句子:This sentence contains word "cate"
未完待續。。。
本文轉自jooben 51CTO部落格,原文連結:http://blog.51cto.com/jooben/318583