java中正则表达式\\b和\\B如何使用,请具体举例说明两者的使用
时间: 2023-09-07 22:12:33 浏览: 104
在Java中,正则表达式中的`\b`和`\B`表示单词边界和非单词边界。
`\b`表示单词边界,即单词的开头或结尾。具体来说,它匹配单词字符和非单词字符之间的位置。例如,`\bhello\b`可以匹配"hello world"中的"hello",但不会匹配"oh hello"中的"hello"。
`\B`表示非单词边界,即不在单词开头或结尾的位置。例如,`\Bhello\B`可以匹配"oh hello world"中的"hello",但不会匹配"hello"或"hello world"。
下面是两者的具体使用示例:
```
String str = "hello world, hello!";
// 匹配单词边界,即匹配"hello",但不匹配"oh hello"
Pattern pattern1 = Pattern.compile("\\bhello\\b");
Matcher matcher1 = pattern1.matcher(str);
while (matcher1.find()) {
System.out.println(matcher1.group());
}
// 匹配非单词边界,即匹配"hello",但不匹配"oh hello"和"hello world"
Pattern pattern2 = Pattern.compile("\\Bhello\\B");
Matcher matcher2 = pattern2.matcher(str);
while (matcher2.find()) {
System.out.println(matcher2.group());
}
```