Java String replaceAll() Method
Last Updated :
23 Dec, 2024
Improve
String replaceAll method in Java searches for a specified string or regex pattern and returns a new string with the matched characters replaced.
Example 1:
class Geeks
{
public static void main(String args[])
{
String str = new String("Welcome to geeksforgeeks");
// Using replaceAll to replace regex with
// replace_str
System.out.print( "After replacing regex with" + " replace_str : ");
System.out.println(str.replaceAll("(.*)geeks(.*)", "GFG"));
}
}
Output
After replacing regex with replace_str : GFG
This method replaces each substring of the string that matches the given regular expression with the given replace_str.
Syntax
public String replaceAll(String regex, String replace_str)
Parameters:
- regex: the regular expression to which this string is to be matched.
- replace_str: the string which would replace found expression.
Return Value: This method returns the resulting String.
Example 2: Invalid regex when passed in raplaceAll() method, raises PatternSyntaxException.
import java.io.*;
class Geeks {
public static void main(String[] args) {
String str = "GFG";
// Incorrect Regular expression
String regex = "\\";
// Passing null expression in
// replaceAll method
str = str.replaceAll(regex, " ");
System.out.println(str);
}
}
Output
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
at java.base/java.util.regex.Pattern.error(Pattern.java:2027)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1788)
at java.base/java.util.regex.Pattern.<init>(Pattern.java:1428)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1068)
at java.base/java.lang.String.replaceAll(String.java:2126)
at GFG.main(GFG.java:11)
Example 3: The null regular expression is not accepted by the replaceAll() method, it raises the NullPointerException.
import java.io.*;
class Geeks {
public static void main(String[] args) {
// input string
String str = "GFG";
// NULL Regular expression
String regex = null;
// Passing null expression in
// replaceAll method
str = str.replaceAll(regex, " ");
System.out.println(str);
}
}
Output
Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.regex.Pattern.<init>(Pattern.java:1426)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1068)
at java.base/java.lang.String.replaceAll(String.java:2126)
at GFG.main(GFG.java:11)