“String.replaceAll()” is one of the built-in methods of the String class. It lets us replace all the occurrences of a specific substring with another substring and retrieves the new(modified) string. In Java, strings are immutable(not changeable), which means they can’t be modified/changed once they are initialized/created. Therefore, when we call/use the replaceAll() method, it retrieves a new string with the specified replacements rather than modifying the actual string.
This write-up will demonstrate the basic signature of the replaceAll() method, its use cases, and potential exceptions that might occur while using this method.
How to Use String.replaceAll() Method in Java
The “String.replaceAll()” method accepts two arguments a “regex_pattern” and a “replacement_string”, as demonstrated in the below syntax:
str.replaceAll(String regex_pattern, String replacement_string);
Where “str” is a target string, “regex_pattern” is a string/regex to be matched, and “replacement_string” is a new string that will replace regex_pattern. This way, all the occurrences of the “regex_pattern” in the target string “str ” will be replaced with the new string “replacement_string”.
Let’s implement it practically to have a profound understanding of this method.
Example 1: Replacing all Occurrences of a Word
In the below code, we use the replaceAll() method to replace all occurrences of “Java” with “Python”:
public class JavaReplaceAll {
public static void main(String[] args) {
String inputString = "Welcome to JavaBeat. Let's learn Java. The Best Site for Java tutorials.";
String updatedString = inputString.replaceAll("Java","Python");
System.out.println("Original String ==> " + inputString);
System.out.println("Modified String ==> " + updatedString);
}
}
From the output snippet, you can observe that the string has been successfully updated with the specified string, i.e., “Python”:
Example 2: Replacing All Whitespaces With a Comma
You can also use the replaceAll() method to replace a special character, delimiter, etc. with a specific substring or character:
String updatedString = inputString.replaceAll(" ",",");
Here, we invoke the replaceAll() method on the given string with whitespace as its first argument and a comma as its second argument. As a result, all the whitespaces in the given string will be replaced with the comma “,”, as shown in the below output:
Example 3: Removing All Whitespaces From a String
You can remove any specific character, word, or whitespaces, from a string by replacing them with an empty/blank substring “”. For instance, in the below code, we use the replaceAll() method to replace the whitespaces with empty strings:
String updatedString = inputString.replaceAll(" ","");
The output shows that all whitespaces have been successfully removed from the string “inputString”:
Example 4: Removing All Occurrences of a Specific Word From a String
Let’s invoke the replaceAll() method on the same “inputString” to remove all occurrences of “Java” from it:
String updatedString = inputString.replaceAll("Java", "");
As expected, the inputString has been modified according to the specified criteria:
Example 5: Removing Numbers From a String
One significance of the replaceAll() method is that it allows us to replace/modify a string based on a regex pattern. For instance, in the following example, we use the regex pattern “[0-9]” to replace the numeric characters with an empty string:
String inputString = "Wel2323come to Java1122Beat12345.net";
String updatedString = inputString.replaceAll("[0-9]", "");
The output shows that all the numbers have been removed from the given string:
Example 6: Replacing All Occurrences of a Specific Character
The below code demonstrates how can you replace a specific character with some other character using the replaceAll() method:
String inputString = "Welcome to JavaBeat.net";
String updatedString = inputString.replaceAll("e","_");
The output snippet indicates that all occurrences of the character “e” have been replaced with the character “_”:
String.replaceAll() Vs String.replace() – What’s the Difference
Both methods serve the same purpose (i.e., replace a string with another string). However, the replaceAll() is more flexible as it allows us to replace the strings based on regex patterns. On the other hand, the replace() method doesn’t support the regex patterns.
What are the Alternatives to the replaceAll() Method in Java
The below table illustrates the best-possible alternatives of the replaceAll() method along with their pros and cons:
Method | Description | Syntax | Pros and Cons |
---|---|---|---|
replace() | This method searches for a specific character sequence in the given string and replaces it with a new specified character sequence. | str.replace(char searchChar, char newChar); | Efficient, faster, and Easy to use.Doesn’t Support regex. |
StringBuilder | It lets us modify the original/given string instead of creating/returning a new string. Later, we can replace any substring with another substring without creating a new string. | new StringBuilder(String inputString); | Better (efficient) than replace() and replaceAll() methods. It deals with large strings efficiently.It is difficult to use and doesn’t support regex. |
StringUtils.replaceAll() | This method belongs to the StringUtils class of the library “Apache common lang”. It replaces all occurrences of the specified substring with another substring (based on the given regex/string). | StringUtils.replaceAll(); | It is null-safe and supports regex.It is deprecated. |
Possible Exceptions While Working With the String.replaceAll() Method
Use the replaceAll() method carefully, otherwise, you may encounter different exceptions, as demonstrated below
1: NullPointerException
The “NullPointerException” is one of the most frequently faced exceptions in Java. This exception occurs while dealing with null strings. As a result, the normal flow of the program gets interrupted/stopped:
String inputString = null;
String updatedString = inputString.replaceAll(" ", "_");
In this code, we invoke the replaceAll() method on a null string as a result, we encounter the following exception:
To fix this exception, we must invoke the replaceAll() method within a try-catch block, as shown below:
public class JavaReplaceAll {
public static void main(String[] args) {
String inputString = null;
try {
String modifiedString = inputString.replaceAll(" ", "");
System.out.println(modifiedString);
} catch (NullPointerException excep) {
System.out.println("Please Specify a Valid Non-null String");
}
}
}
Here you go! The program executes successfully and demands the user to invoke the replaceAll() method on a valid string:
2: PatternSyntaxException
While working with regular expressions you must specify the regex pattern carefully. Otherwise, you may encounter the PatternSyntaxException exception, as shown below:
String inputstring = "Welcome to JavaBeat(.net)!";
String modifiedString = inputstring.replaceAll("(.", "{.");
System.out.println(modifiedString);
Import the “PatternSyntaxException” class in your program and use it in the try-catch block to identify and fix the stated exception:
import java.util.regex.PatternSyntaxException;
public class JavaReplaceAll {
public static void main(String[] args) {
String inputstring = "Welcome to JavaBeat(.net)!";
try {
String modifiedString = inputstring.replaceAll("(.", "{.");
System.out.println(modifiedString);
} catch (PatternSyntaxException excep) {
System.out.println("Please Specify a Valid Regex Pattern");
}
}
}
This time a custom message is shown on the console, instructing the user to specify a valid syntax. This way the normal flow of the program wouldn’t be disrupted and the rest of the statements would execute successfully:
That’s all about Java’s “String.replaceAll()” method.
Final Thoughts
The “String.replaceAll()” method in Java is used to replace all occurrences of a specific character, word, or substring, with a new character, word, or substring. You can invoke this method on the target string with a regex pattern and a replacement string. As a result, it retrieves a new(modified) string with the replaced/updated substring(s). However, If you invoke the replaceAll() method on a null string you will face a “NullPointerException”. Similarly, a “PatternSyntaxException” will be raised in case you specify an inappropriate regex pattern in the replaceAll() method. This Java post has extensively explained the working of the replaceAll() method, its different use cases, alternatives, and possible exceptions.