Open In App

How to Replace All Occurings of String Using Regex in Java?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Regex in Java is an interesting way to search for patterns in a string that the user provides. Expanded as Regular Expressions, It consists of some patterns that can be planned and modified according to the usage in the program.

Example of Replace All Occurings of a String

Input: str=”This is a sample string and it doesn’t exist in real world. Refer to GFG for real String related data”;
to_Replace=”string”
final_element=”…..”

Output: This is a sample ….. and it doesn’t exist in real world. Refer to GFG for real ….. related data

Java Program to Replace all Occurrence of String

Below is the implementation of Replace all Occurrence of String :

Java




// Java Program to Replace
// all Occurrence of String
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 = "I am A Normal Person and a normal human being";
  
        String replacementString = "Extraordinary";
        
          String original_element="normal";
  
          // String that is to be replaced
        String searchString = "\\b(?i)" + original_element + "\\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.replaceAll(replacementString); 
  
        System.out.println("Original String: " + inputString);
        System.out.println("Result String: " + resultString);
    }
}


Output

Original String: I am A Normal Person and a normal human being
Result String: I am A Extraordinary Person and a Extraordinary human being

Explanation of the above code:

  • To replace all the specified word in the string with given replacement String , we make use of the regex pattern matcher.
  • First we have to provide the 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 occurance with the replaceAll() method.

Note: (?i) ignores the case and \\b is used for word boundaries to ensure that only whole words are matches



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads