如何在 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 次瀏覽

開啟您的職業生涯

完成課程,獲得認證

入門
廣告