Open In App

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

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

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


Article Tags :