如何使用 Java 中的 Pattern 类匹配字符串中的特定单词?

javaobject oriented programmingprogramming更新于 2024/5/11 3:24:17

Java 正则表达式中的 \b 元字符与单词边界匹配,因此,要从给定的输入文本中找到特定单词,请在正则表达式中的单词边界内指定所需单词为 −

"\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("输入输入字符串");
      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");
      }
   }
}

输出

输入输入字符串
hello welcome to Tutorialspoint
匹配结果

示例 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

相关文章


有用资源