What is RegExUtils.replaceAll in Java?
What is the replaceAll method?
The replaceAll method is a
RegExUtils class that is used to replace all the substrings in a given string that match the specified regular expression with the replacement value.
Add the Apache Common Lang package
RegExUtils is defined in the Apache Commons Lang package. To add the Apache Commons Lang to the Maven project, add the following dependency to pom.xml file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
How to import RegExUtils
RegExUtils class can be imported as follows.
import org.apache.commons.lang3.RegExUtils;
Syntax
public static String replaceAll(final String text, final Pattern regex, final String replacement)
Parameters
-
final String text: The string on which the regex is applied. -
final Pattern regex: regular expression. -
final String replacement: replacement string.
Return value
This function returns the modified text after replacing the substrings that match the regex with the replacement string.
Code
In the code below, we define a text that has educative word repeated multiple times in the text. Next, we use the replaceAll method to replace the word educative from the text with the word edpresso.
import org.apache.commons.lang3.RegExUtils;import java.util.regex.Pattern;public class Main {public static void main(String[] args){String text = "educative is the best platform for java. educative is the best platform for python. educative is the best platform for c.";System.out.println(RegExUtils.replaceAll(text, Pattern.compile("educative"), "edpresso"));}}
Output
The output of the code when executed would be as follows.
edpresso is the best platform for java. edpresso is the best platform for python. edpresso is the best platform for c.