Java String replaceAll() Method
Last Updated :
20 Aug, 2023
The String replaceAll method in Java searches for a specified string or a specified value, or a regex expression by virtue of which has the same suggests returns a new string with related characters. Let us learn about Java replaceAll string method in this article.
Java String replaceAll()
This method replaces each substring of the string that matches the given regular expression with the given replace_str.
Syntax of Java replaceAll String
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 of String.replaceAll Method in Java
Java
public class rep2 {
public static void main(String args[])
{
String Str = new String( "Welcome to geeksforgeeks" );
System.out.print( "Original String : " );
System.out.println(Str);
System.out.print(
"After replacing regex with replace_str : " );
System.out.println(
Str.replaceAll( "(.*)geeks(.*)" , "ASTHA TYAGI" ));
}
}
|
Output
Original String : Welcome to geeksforgeeks
After replacing regex with replace_str : ASTHA TYAGI
Exceptions with String.replaceAll Java
Although the String replaceAll method is very effective in Java but even it comes up with certain exceptions as mentioned below:
1. Invalid regex
Invalid regex when passed in raplaceAll() method, raises PatternSyntaxException.
Example:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String str = "GFG" ;
System.out.println(str);
String regex = "\\" ;
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)
2. Null regular expression
The null regular expression is not accepted by the replaceAll() method, it raises the NullPointerException.
Example:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String str = "GFG" ;
System.out.println(str);
String regex = null ;
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)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...