如何使用Java中的Pattern类匹配字符串中的特定单词?
该\b在Java正则表达式元字符单词边界匹配。因此从给定的输入文本找到一个特定的词指定正则表达式的字边界内所需的字作为-
"\\brequired word\\b";
例子1
import 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
例子2
import 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
热门推荐
10 生日宝宝祝福语简短独特
11 祖国七十华诞简短祝福语
12 新年简短的祝福语爱情
13 祝贺开业文案祝福语简短
14 幼儿狗年祝福语大全简短
15 老师祝福语简短100字
16 祝美术老师祝福语简短
17 新年酒席开席祝福语简短
18 好听的元旦简短祝福语