Horje
Java Program to Search a Particular Word in a String Using Regex

In Java string manipulation, searching for specific words is a fundamental task. Regular expressions (regex) offer a powerful and flexible approach to achieve this search. It matches the patterns simply by comparing substrings.

In this article, we will learn how to search for a particular word in a string using regex in Java.

Regular Expressions:

  • Patterned expressions are used to represent sequences of characters and match them against text.
  • Composed of special characters and metacharacters with specific meanings.

Word Boundaries:

  • Ensures that matches occur as complete words rather than parts of other words.
  • Represented by \b in regex patterns.

Step-by-Step Implementation

Step 1: Import java.util.regex

import java.util.regex.*;

Step 2: Compile the Regex Pattern

  • Create a Pattern object using Pattern.compile().
  • Enclose the word you want to search for (e.g., “Java”) within word boundaries \b.
  • Optionally, use case-insensitive matching with Pattern.CASE_INSENSITIVE.
String word = "Java"; // Word to search for
Pattern pattern = Pattern.compile("\\b" + word + "\\b", Pattern.CASE_INSENSITIVE);

Step 3: Create a Matcher

  • Instantiate a Matcher object using the compiled pattern and the string to search.
  • find() attempts to find the first occurrence of the word.
String text = "This is a string containing the word Java.";
Matcher matcher = pattern.matcher(text);

Step 4: Iterate and Process Matches

  • Use a loop to iterate through matches using find().
  • Extract matched words:
    • start() returns the index of the match’s first character.
    • end() returns the index after the last character (non-inclusive).
    • Use substring extraction to get the matching word.

Example with output formatting:

while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
String match = text.substring(start, end);
System.out.println("Found word \"" + match + "\" at index [" + start + ", " + (end - 1) + "]");
}

Step 5: Handling No Matches

  • If find() doesn’t find any matches, inform the user or handle it within your logic.

Program to Search a Particular Word in a String Using Regex in Java

Java

// Java program to search a particular word in a string using regex
import java.util.regex.*;
  
// Driver Class
public class GFG {
      // Main Function
    public static void main(String[] args)
    {
          // word to search for
        String word = "Java";    
        String text
            = "This is a string containing the word Java. And another Java.";
        Pattern pattern = Pattern.compile(
            "\\b" + word + "\\b", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(text);
  
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            String match = text.substring(start, end);
            System.out.println("Found word \"" + match
                               + "\" at index [" + start
                               + ", " + (end - 1) + "]");
        }
    }
}

Output

Found word "Java" at index [37, 40]
Found word "Java" at index [55, 58]




Reffered: https://www.geeksforgeeks.org


Java

Related
How does the 'accessOrder' Configuration in LinkedHashMap Work? How does the 'accessOrder' Configuration in LinkedHashMap Work?
How to Convert a PriorityQueue into an Array, List, and Set in Java? How to Convert a PriorityQueue into an Array, List, and Set in Java?
How to Create an Immutable TreeMap in Java and it's Benefits? How to Create an Immutable TreeMap in Java and it's Benefits?
How to Execute a SQL Query Using JDBC? How to Execute a SQL Query Using JDBC?
How does HashTable Handle HashCode Distribution in Java? How does HashTable Handle HashCode Distribution in Java?

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