正则表达式 学习笔记4.1

徒弟: 前面 几节课跟师傅学习了 字符组,括号的作用 ,还有什么呢? <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

师傅:还有好多呀,例如锚点!
问题引出:

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 =  "\\ b cat\\ 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 !
 
未完待续。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值