徒弟:前面几节课跟师傅学习了字符组,括号的作用,还有什么呢?
师傅:还有好多呀,例如锚点!
问题引出:
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,而不能匹配单词cat
再试试:
String str = "This sentence contains word cate";
String regex = "\\scat\\s";
要求cat两端出现空白字符,运行结果:
没有找到 cat !
此时,正确发现不包含单词cat
如果是这样呢?
String str = "This sentence contains word cat";
String regex = "\\scat\\s";
运行结果:
没有找到 cat !
按道理,应该是包含的,只是在末尾没有空格
如果这样子呢:
String str = "This sentence contains word 'cat'";
String regex = "\\scat\\s";
当然,实际情况,可能会更加复杂,需要一种办法解决:锚点
锚点
作用:规定匹配的位置
形式:\b 单词分界符锚点
规定在反斜线的一侧必须出现的单词,另一侧不可以出现单词字符。
例子:
public class GeneralTwo {
public static void main(String[] args) {
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);
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
if(m.find()){
System.out.println("找到 cat !");
}else{
System.out.println("没有找到 cat !");
}
}
}
}
运行结果:
处理句子:This sentence contains word cat
找到 cat !
处理句子:This sentence contains word 'cat'
找到 cat !
处理句子:This sentence contains word vacation
没有找到 cat !
处理句子:This sentence contains word "cate"
没有找到 cat !
 
未完待续。。。