How to Replace a String Using Regex Pattern in Java?
Last Updated :
07 Feb, 2024
Improve
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
- Now we have to use Pattern.compile() to create a Pattern object that will represent our regex pattern.
- After that, we have to enclose the pattern within a raw string ("\\d+") to avoid the escaping backslashes.
Step 3: Create a Matcher object
- Now we have to use the matcher() method of Pattern object so that we can create a Matcher object that will search for matches in a string.
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:
- The above Java program demonstrates replacing a string using
replaceAll()
and a regex pattern. - It starts with an input string containing numbers.
- The program defines a regex pattern to match digits (
\\d+
) and a replacement string ("number"
). - It then uses
replaceAll()
to replace all occurrences of digits in the input string with the replacement string. - After that it will print the original and modified strings.
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:
- The above Java program replaces a string using
Matcher
and a regex pattern. - It starts with an input string containing multiple occurrences of the word "apple."
- The program defines a regex pattern to match the word "apple" and a replacement string ("orange").
- It uses
Pattern.compile()
method to create a pattern andMatcher
to find and replace occurrences iteratively. The modified string is then printed.