Horje
Java Program to Find Occurrence of a Word Using Regex

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



Reffered: https://www.geeksforgeeks.org


Java

Related
Immutable Array in Java Immutable Array in Java
Validate a Time Format (HH:mm:ss) Using Regex in Java Validate a Time Format (HH:mm:ss) Using Regex in Java
How to Replace All Occurings of String Using Regex in Java? How to Replace All Occurings of String Using Regex in Java?
How to Match Phone Numbers in a List to a Regex Pattern in Java ? How to Match Phone Numbers in a List to a Regex Pattern in Java ?
Base64 Java Encode and Decode a String Base64 Java Encode and Decode a String

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11