天天看点

正则表达式 学习笔记4.2

单词分界符注意事项:

l \b 表示单词分界符,要求一侧是单词字符,另一侧是非单词字符

l 单词字符通常指的是英文字符、数字字符,对中文不适用

l 非单词字符通常指的是各种标点符号和空白字符

例子:

public class GeneralThree {

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\"",

"句子里包含的英文单词cat0在这里",

"句子里包含的英文单词cat在这里"

};

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'

处理句子:This sentence contains word vacation

没有找到 cat !

处理句子:This sentence contains word "cate"

处理句子:句子里包含的英文单词cat0在这里

处理句子:句子里包含的英文单词cat在这里

可见:

第三个、\b不能区分t0英文字符和数字字符之间的位置。

第四个、\b不能区分t在英文字符和中文字符之间的位置。

锚点:

l ^ 匹配一行的开头(有可能变化)

l $ 匹配一行的结尾(有可能变化)

l \A 匹配整个字符串的开头

l \Z 匹配整个字符串的末尾

^和$在不同的匹配模式下,可能有所变化,匹配模式的概念将在下一节课介绍。

默认情况下:

^等于\A 用来匹配整个字符串的开头

$等于\Z 用来匹配整个字符串的结尾

如果匹配某一个逻辑行的开头,和某一个逻辑行的结尾?

这个需要更改匹配模式。

看看这四个锚点的基本应用。

public class GeneralFour {

String[] strings = {"start"," start "," end ","end"};

String[] regexs = {"^start","\\Astart","end$","end\\Z"};

for(String regex:regexs){

System.out.println(str+"能够匹配正则:"+regex);

System.out.println(str+"不能够匹配正则:"+regex);

处理句子:start

start能够匹配正则:^start

start能够匹配正则:\Astart

start不能够匹配正则:end$

start不能够匹配正则:end\Z

处理句子: start 

 start 不能够匹配正则:^start

 start 不能够匹配正则:\Astart

 start 不能够匹配正则:end$

 start 不能够匹配正则:end\Z

处理句子: end 

 end 不能够匹配正则:^start

 end 不能够匹配正则:\Astart

 end 不能够匹配正则:end$

 end 不能够匹配正则:end\Z

处理句子:end

end不能够匹配正则:^start

end不能够匹配正则:\Astart

end能够匹配正则:end$

end能够匹配正则:end\Z

下面一个功能:

环视

l 锚点对位置的判断不够灵活

l 作用:应用子表达式对位置进行判断

l 形式:

· (?=...)

· (?!...)

· (?<...)

· (?<!...)

形式

名称

匹配意义

(?=...)

肯定顺序环视

右侧文本能由子表达式匹配

(?!...)

否定顺序环视

右侧文本不能由子表达式匹配

(?<...)

肯定逆序环视

左侧文本能由子表达式匹配

(?<!...)

否定逆序环视

左侧文本不能由子表达式匹配

首先看看顺序环视结构的例子:

public class GeneralFive {

String[] strings = new String[]{"Jeff","Jeffrey","Jefferson"};     

String[] regexs = new String[]{"Jeff","Jeff(?=rey)","Jeff(?!rey)"};

System.out.println("\"" + str +"\" 能够匹配正则:"+regex);

System.out.println("\"" + str +"\" 不能够匹配正则:"+regex);

System.out.println("");

"Jeff" 能够匹配正则:Jeff

"Jeffrey" 能够匹配正则:Jeff

"Jefferson" 能够匹配正则:Jeff

"Jeff" 不能够匹配正则:Jeff(?=rey)

"Jeffrey" 能够匹配正则:Jeff(?=rey)

"Jefferson" 不能够匹配正则:Jeff(?=rey)

"Jeff" 能够匹配正则:Jeff(?!rey)

"Jeffrey" 不能够匹配正则:Jeff(?!rey)

"Jefferson" 能够匹配正则:Jeff(?!rey)

未完待续。。。

本文转自jooben 51CTO博客,原文链接:http://blog.51cto.com/jooben/318584

继续阅读