Skip to content

Java String replace() and replaceAll() method

In this tutorial, we will see how the replace() and 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)

Syntax

String.replace(oldChar, newChar);
String str1 = "Start_!___!___!___!_start";
System.out.println("Single Character: " + str1.replace("!","+"));
System.out.println("Character Sequence: " + str1.replace("start","End"));

Output

Single Character: Start_+___+___+___+_start
Character Sequence: Start_!___!___!___!_End

2. replaceAll() method

Replaces each string which matches to the regex with the newChar.

Note:

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.

Syntax

String.replaceAll(regex, newChar);
String str1 = "XYZ 123 A78R";
System.out.println(str1.replaceAll("\\d",""));

Output

XYZ AR

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.