How to match a particular word in a string using Pattern class in Java?


The \b meta character in Java regular expressions matches the word boundaries Therefore to find a particular word from the given input text specify the required word within the word boundaries in the regular expressions as −

"\brequired word\b";

Example 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");
      }
   }
}

Output

Enter input string
hello welcome to Tutorialspoint
Match found

Example 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");
      }
   }
}

Output

Match found

Updated on: 21-Nov-2019

872 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements