English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to use the Pattern class in Java to match specific words in a string?

the\bIn Java regular expression word boundary meta-character matching. Therefore, find a specific word from the given input text within the word boundary specified by the regular expression as-

"\\brequired word\\b"

Example1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MachingWordExample1 {
   public static void main( String args[] ) {
      //Read string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.next();
      //Regular expression to find numbers
      String regex = "\\bhello\\b";
      //Compile regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieve matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      {}
   {}
{}

Output Result

Enter input string
hello welcome to w3codebox
Match found

Example2

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";
      //Compile regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieve matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      {}
   {}
{}

Output Result

Match found