All about .replaceAll() in Java

Udith Gayan Indrakantha
2 min readOct 21, 2019

--

java.lang.String class brings you a very powerful method to do replacements within a string.

This method allows you to target specific substrings using regular expression ,so that you can even remove and replace any pattern within a string.

Mainly, this method can

  • replace a given substring found any where in the string
  • replace a given character found any where in the string
  • replace a given reg expression found any where in the string

Even though there are separate methods like replace(char old, char new), replace(charSequence old, charSequence new) to do above functions, this replaceAll() method acts as a versatile method for all those functions.

This is how this method is defined in String class,

String replaceAll(String regex , String new)

As you can see , this method returns a new string. Actually, a string is immutable in JAVA , so it is not possible to alter a string. This method returns a new string instead.You need to catch it with a string variable.

*This method accepts to two parameters which must be in type String. So , when you need to replace a character, you have to use a double quotation for the characters (instead of single quotations which are used for representing char).

Examples:

Character replacement
String replacement
Regex replacement

Keep in Touch!!!

--

--