Open In App

How to Replace the First Occurrence of a String Using Regex in Java?

Regex is a very interesting way to search for patterns in a String that the user provides. Regex stands for Regular Expressions. It consists of some patterns that can be planned and modified according to the usage of the program.

In this article, we will discuss how to replace the first occurrence of a String using regex in Java.



Example to Replace the First Occurrence of String

Input: str = "Hello World . World is beautiful"
element = “World”
replace_element= “GFG”

Output: Hello GFG . World is beautiful



Java Program to replace the first occurrence of a String using regex

Below is the code implementation to replace the first occurrence of a String using regex:




// Java Program to replace the first occurrence of a String using regex
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
// Driver Class
class GFG {
      // Main Function
    public static void main(String[] args)
    {
        String inputString = "She is A Good Person . A good person is not always extraordinary";
  
        String replacementString = "Extraordinary";
  
        // String that is to be replaced
        String searchString = "\\b(?i)good\\b";
  
        Pattern regex = Pattern.compile(searchString);
  
        // Create a matcher for the input
        // string
        Matcher matcher = regex.matcher(inputString);
  
        // Use replaceAll to replace all
      //occurrences of the Regex
        String resultString
            = matcher.replaceFirst(replacementString);
  
        System.out.println("Original String: " + inputString);
        System.out.println("Result String: " + resultString);
    }
}

Output
Original String: She is A Good Person . A good person is not always extraordinary
Result String: She is A Extraordinary Person . A good person is not always extraordinary

Explanation of the above Program:


Article Tags :