Java Program to Find Occurrence of a Word Using Regex
Last Updated :
31 Jan, 2024
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
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WordOccurrencesExample {
public static void main(String[] args) {
String text = "Java is a versatile programming language. Java is widely used in software development." ;
String wordToFind = "Java" ;
Pattern pattern = Pattern.compile( "\\b" + wordToFind + "\\b" , Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(text);
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
Share your thoughts in the comments
Please Login to comment...