Home »
Java »
Java Programs
Java program to replace a substring with another substring into the string at all places using regular expression
Java example to replace a substring with another substring into the string at all places using regular expression.
Submitted by Nidhi, on June 13, 2022
Problem statement
In this program, we will create a string and a regular expression pattern. Here we will replace a substring pattern with another substring using the replaceAll() method.
Source Code
The source code to replace a substring with another substring into string at all places using regular expression is given below. The given program is compiled and executed successfully.
// Java program to replace a substring with another substring
// into the string at all places using regular expression
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String str = "abc pqr abc lmn xyz";
String regex = "abc";
String replace = "123";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
str = matcher.replaceAll(replace);
System.out.println(str);
}
}
Output
123 pqr 123 lmn xyz
Explanation
In the above program, we imported the "java.util.regex.*" package to use the Pattern and Matcher classes. Here, we created a public class Main.
The Main class contains a main() method. The main() method is the entry point for the program. And, created a string and pattern. Then we used the replaceAll() method to replace a substring pattern "abc" with another substring "123", and printed the updated string.
Java Regular Expressions Programs »