如何使用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
热门推荐
5 短祝福语简短暖心
10 结婚祝福语粤语大全简短
11 晚上祝福语女生文案简短
12 法语妈妈生日祝福语简短
13 药厂开工祝福语大全简短
14 蛋糕节日祝福语简短英文
15 跨年的生日祝福语简短
16 文案祝福语英文短句简短
17 在家聚餐婚礼祝福语简短
18 学生节祝福语大全简短