How to search a particular word in a string using Java



Problem Description

How to search a particular word in a string?

Solution

Following example demonstrates how to search a particular word in a string with the help of matcher.start() method of regex.Matcher class.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("j(ava)");
      String candidateString = "This is a java program. This is another java program.";
      Matcher matcher = p.matcher(candidateString);
      int nextIndex = matcher.start(1);
      
      System.out.println(candidateString);
      System.out.println("The index for java is:" + nextIndex);
   }
}

Result

The above code sample will produce the following result.

This is a java program. This is another java program.
The index for java is: 11

The following is an example to search a particular word in a string.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
   public static void main(String[] args) {
      String s1 = "sairamkrishna mammahe Tutorials Point Pvt Ltd";
      String regex = "\\bPoint\\b";
      Pattern p1 = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
      Matcher m1 = p1.matcher(s1);
      
      while (m1.find()) {
         System.out.print("Start index: " + m1.start());
         System.out.print(" End index: " + m1.end() + " ");
         System.out.println(m1.group());
      } 
   }
}

The above code sample will produce the following result.

Start index: 32 End index: 37 Point
java_regular_exp.htm
Advertisements