Open In App

Java Program to Find Occurrence of a Word Using Regex

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Java’s regular expressions, or regex, let you do advanced text manipulation and matching. Regex offers a handy approach for searching for a term in a text wherever it appears. In this article, we will learn to find every occurrence of a word using regex.

Program to Find Occurrence of a Word Using Regex

The primary idea is to use Java’s java.util.regex library, namely the Pattern and Matcher classes. You may create a pattern that matches a certain word or character sequence using regular expressions. The Matcher class assists in locating instances of the pattern within a supplied text, while the Pattern class assembles the regex pattern.

Below is the implementation of finding the occurrence of a word using Regex:

Java




// Java program to find occurrences of a 
// specific word in a given text using regular expressions
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
// Class definition for WordOccurrencesExample
public class WordOccurrencesExample {
    // Main method
    public static void main(String[] args) {
        // Create a sample text
        String text = "Java is a versatile programming language. Java is widely used in software development.";
  
        // Define the word to find occurrences
        String wordToFind = "Java";
  
        // Create a regex pattern using the word
        Pattern pattern = Pattern.compile("\\b" + wordToFind + "\\b", Pattern.CASE_INSENSITIVE);
  
        // Create a matcher for the text
        Matcher matcher = pattern.matcher(text);
  
        // Find and display every occurrence of the word
        System.out.println("Occurrences of the word '" + wordToFind + "':");
        while (matcher.find()) {
            System.out.println("Found at index " + matcher.start() + " - " + matcher.group());
        }
    }
}


Output

Occurrences of the word 'Java':
Found at index 0 - Java
Found at index 42 - Java



Explaination of the above Program:

  • Create a sample text
  • Define the word to find occurrences
  • Create a regex pattern using the word
  • Create a matcher for the text
  • Find and display every occurrence of the word

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads