Java String replace() and replaceAll() method
In this tutorial, we will see how the
replaceAll() works and what’s the difference between these two methods. All of these Java String methods are mainly using for replacing the String with another String.
1. replace() method
It replaces all the occurrence of oldChar with newChar in the String with case sensitivity. Can use this method if you want to replace some char with another char or some String to another String(Character Sequence)
String str1 = "Start_!___!___!___!_start"; System.out.println("Single Character: " + str1.replace("!","+")); System.out.println("Character Sequence: " + str1.replace("start","End"));
Single Character: Start_+___+___+___+_start Character Sequence: Start_!___!___!___!_End
2. replaceAll() method
Replaces each string which matches to the regex with the newChar.
backslash(\) and dollar($) in the replacement string cause the different result. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters. You can use replaceFirst() to replace only first occurrence which matches to the regex.
String str1 = "XYZ 123 A78R"; System.out.println(str1.replaceAll("\\d",""));
replace() method is bit faster
replaceAll() if the performance is concerned, because
replaceAll() will compiles the regex pattern and then replace the matched. But
replace() simply replaces all the matched character.