Computer >> Máy Tính >  >> Lập trình >> Java

Làm cách nào để so khớp một từ cụ thể trong một chuỗi bằng cách sử dụng lớp Mẫu trong Java?

\ b ký tự meta trong biểu thức chính quy Java khớp với các ranh giới từ Do đó, để tìm một từ cụ thể từ văn bản đầu vào đã cho, hãy chỉ định từ bắt buộc trong các ranh giới từ trong biểu thức chính quy là -

"\\brequired word\\b";

Ví dụ 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");
      }
   }
}

Đầu ra

Enter input string
hello welcome to Tutorialspoint
Match found

Ví dụ 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");
      }
   }
}

Đầu ra

Match found