Open In App

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

Last Updated : 02 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// 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:

  • To replace the first occurance in the string with given replacement String, we make use of the regex pattern matcher.
  • First, we have to provide a pattern that matches exactly with the Input String.
  • Then With the Pattern.compile() method we compile the regex pattern to a String.
  • Then matcher function is used to extract the matched word from the Input String.
  • After obtaining the matched word It is much easier to replace all its first with the replaceFirst() method.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads