Java String replaceAll() Method
Java’s String replaceAll function creates a new string with characters that are related to a supplied string, a defined value, or a regex expression.
Explanation
The replaceAll() method of the Java String class returns a string that replaces all the characters in the regex and replacement string sequence.
Each substring in the string that matches the regex is replaced with the supplied text using the replaceAll() method.
Syntax:
public String replaceAll(String regex, String replace_str)
Internal implementation
public String replaceAll(String regex, String replacement) {
return
Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
Parameter:
- regex: the regular expression that will be used to match this string.
- replace_str: the string that will be used to replace the found expression.
Return Value:
- This method gives back the finished String.
- Returns a new string that replaces every instance of the matching substring with the replacement string.
Diagram:
Example:
For instance, to replace all occurrences of a single character:
public class TechVidvanReplaceAll{
public static void main(String args[]){
String s1="Good things takes time";
String replaceString=s1.replaceAll("o","e");
System.out.println(replaceString);
}
}
Output:
Good things takes time
Example:
For example, to replace all occurrences of a single word or collection of terms:
public class TechVidvanReplaceAll{
public static void main(String args[]){
String s1="My name is Jaanu, her name is Nithu.";
String replaceString=s1.replaceAll("is","was");
System.out.println(replaceString);
}
}
Output:
My name was Jaanu, her name was Nithu.
Example:
Inserting spaces between characters was done by using the replaceAll() method:
public class ReplaceAllExample5
{
// main method
public static void main(String argvs[])
{
// input string
String str = "Cricket";
System.out.println(str);
String regex = "";
// adding a white space before and after every character of the input string.
str = str.replaceAll(regex, " ");
System.out.println(str);
}
}
Output:
Cricket
C r i c k e t
Escaping Characters in replaceAll()
Whether it is a regex or a regular string, the first argument to the replaceAll() method is up to you, mainly because a regular expression is a typical string.
Regex contains characters with special meanings.
The metacharacters are as follows:
\ ^ $ . | ? * + {} [] ()
Use either the method or the replace() method to match the substring that contains metacharacters.
Difference between replaceAll() and replace()
- The ReplaceAll() method substitutes a new value for every occurrence of a supplied substring. On the other hand, the Replace() function is used to replace particular characters in a string with a new value. It merely swaps out the substring’s first “n” occurrences.
- While the replace() method substitutes a single character, the replaceAll() function replaces a pattern (using regex). On the other hand, the replace() method uses a String as a replacement.
How to replace all characters?
- String.prototype.replaceAll(): A new string is produced by the replaceAll() method of the String data type, and it contains replacements for all pattern matches.
- The replacement can be a string or a function that is called for each match, and the pattern can be either a string or a RegExp. The first string is not altered.
Special Characters
- Be aware that the outcomes might differ from what they would be if the replacement string were treated as a literal replacement string if it contained dollar signs ($) or backslashes ().
Exception of String replaceAll()
Although the String replaceAll method in Java is quite effective, it does have some limitations.
- Invalid regex: When an invalid regex is passed to the replaceAll() method, a PatternSyntaxException with the name Invalid regex is raised.
- Null regular expression: The replaceAll() method throws a NullPointerException and does not accept null regular expressions.
The four primary ways to handle this exception:
| public String getMessage() | The description of the exception is included. |
| public int getIndex() | It will return the error of the index. |
| public String getPattern() | It will return the regular expression that contains the error. |
| public String getDescription() | It will provide us with a decryption for the error. |
Usage of string replaceAll()
- Substrings should be replaced with different strings wherever they appear.
- It is typically employed to eliminate characters or their pattern from a String.
- It can easily escape in particular expressions by using the replaceAll() method.
Advantages of String replaceAll()
- Replace: It replaces every instance of the given pattern in a string and is repeatable.
- Maintain: It keeps the original string intact while returning a new string with replacement characters..
- Wide range: It offers a selection of techniques for carrying out some replacements.
Disadvantages of String replaceAll()
- Complexity: It contributes to errors in complex expressions and makes the code challenging to understand and maintain.
- Escaping: Because special characters make code harder to read, they should be correctly escaped.
- Not Appropriate: It is not appropriate for single occurrences and substring replacements.
Conclusion
We have discussed the String replaceAll() in Java. In extensively learned about its uses and function of replaceAll().

