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


因此,为了从给定的输入文本中找到特定单词,可以在正则表达式中用单词边界指定所需的单词,如下所示:

"\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[] ) {
      //Reading string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.next();
      //Regular expression to find digits
      String regex = "\bhello\b";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      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 Tutorialspoint
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";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}

输出

Match found

更新日期:2019 年 11 月 21 日

989 次浏览

开启您的职业生涯

完成课程,获得认证

入门
广告
© . All rights reserved.