Open In App

How to Replace a String Using Regex Pattern in Java?

Regular Expressions (regex), in Java, are a tool, for searching, matching, and manipulating text patterns. Regex patterns are usually written as fixed strings. Based on different scenarios we may need to create a regex pattern based on a given string.

In this article, we will learn how to replace a String using a regex pattern in Java.



Step-by-step Implementation

Step 1: Import the java.util.regex package

import java.util.regex.Pattern;
import java.util.regex.Matcher;

Step 2: Define the regex pattern

Step 3: Create a Matcher object

Step 4: Apply the replacement

Program to Replace a String Using Regex Pattern in Java

Method 1: Using replaceAll()

In this example, we will replace string “12345” with “number” by using replaceAll() method.




// Java Program to replace a String using replaceAll() and regex pattern
import java.util.regex.Pattern;
  
public class StringRegexReplacementExample1 {
    public static void main(String[] args) {
        // Original input string
        String inputString = "Hello, world! 12345 world.";
        System.out.println("Original String: " + inputString);
  
        // Regex pattern to match (using corrected escape sequence for digits)
        String regexPattern = "\\d+";
  
        // replacement string
        String replacementString = "number";
  
        // replace all occurrences of the pattern in the input string
        String outputString = inputString.replaceAll(regexPattern, replacementString);
  
        // print the modified string
        System.out.println("Modified String: " + outputString);
    }
}

Output

Original String: Hello, world! 12345 world.
Modified String: Hello, world! number world.

Explanation of the Program:

Method 2: By Using Matcher Methods

In this example we will see how we can replace all “apple” with “orange” by using matcher methods.




// Java Program to replace a String using matcher() and regex pattern
import java.util.regex.Pattern;
import java.util.regex.Matcher;
  
public class StringRegexReplacementExample2 {
    public static void main(String[] args) {
        // Original input string
        String inputString = "apple, banana, apple";
        System.out.println("Original String: " + inputString);
        
        // Regex pattern to match
        String regexPattern = "apple";
          
        // replacement string
        String replacementString = "orange";
  
        // compile the regex pattern
        Pattern pattern = Pattern.compile(regexPattern);
          
        // create a matcher for the input string
        Matcher matcher = pattern.matcher(inputString);
  
        // StringBuilder to store the modified string
        StringBuilder sb = new StringBuilder();
  
        // find and replace occurrences of the pattern in the input string
        while (matcher.find()) {
            matcher.appendReplacement(sb, replacementString);
        }
  
        // append the remaining part of the input string after the last match
        matcher.appendTail(sb);
  
        // get the modified string
        String outputString = sb.toString();
        System.out.println("Modified String: " + outputString);  // Output: orange, banana, orange
    }
}

Output
Original String: apple, banana, apple
Modified String: orange, banana, orange

Explanation of the Program:


Article Tags :