该\ b在Java正则表达式元字符单词边界匹配。因此从给定的输入文本找到一个特定的词指定正则表达式的字边界内所需的字作为-"\\brequired word\\b";
例子1import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MachingWordExample1 {
public static void main( String args[] ) {
//读取字符串值
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string");
String input = sc.next();
//查找数字的正则表达式
String regex = "\\bhello\\b";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
//检索匹配器对象
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
输出结果Enter input string
hello welcome to Nhooo
Match found
例子2import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample2 {
public static void main( String args[] ) {
String input = "This is sample text \n " + "This is second line " + "This is third line";
String regex = "\\bsecond\\b";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
//检索匹配器对象
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
输出结果Match found