1.定位符
下面的表达式匹配单词 Chapter 的开头三个字符,因为这三个字符出现在单词边界后面:
\bCha
\b 字符的位置是非常重要的。如果它位于要匹配的字符串的开始,它在单词的开始处查找匹配项。如果它位于字符串的结尾,它在单词的结尾处查找匹配项。例如,下面的表达式匹配单词 Chapter 中的字符串 ter,因为它出现在单词边界的前面:
ter\b
下面的表达式匹配 Chapter 中的字符串 apt,但不匹配 aptitude 中的字符串 apt:
\Bapt
字符串 apt 出现在单词 Chapter 中的非单词边界处,但出现在单词 aptitude 中的单词边界处。对于 \B 非单词边界运算符,位置并不重要,因为匹配不关心究竟是单词的开头还是结尾。
边界可以定义为开头或结尾。
2.实例学习
例子1:
public static void main(String[] args) {
String str="life is a fuck _movie";
//获得一个正则表达式对象
Pattern p = Pattern.compile("\\blife");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}
例子2:
public static void main(String[] args) {
String str="life is a fuck _movie";
//获得一个正则表达式对象
Pattern p = Pattern.compile("vie\\b");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}
实例3:
public static void main(String[] args) {
String str="life is a fuck _movie";
//获得一个正则表达式对象
Pattern p = Pattern.compile("\\Bvi");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}