java.lang.String replaceAll()

Description :

This java tutorial shows how to use the replaceAll() method of java.lang.String class. This method returns a new String object as a result of replacing all the occurrences of the regex pattern with String parameter replacement.

Method Syntax :

public String replaceAll(String regex,String replacement)

Parameter Input :

[table]
DataType|Parameter|Description
String|regex|Regular expression that we have to use on evaluation if our string qualifies to be reconstructed by replacing characters.
String|replacement|The string to be replaced on our String once the regex pattern satisfies our method search
[/table]

Method Returns :

This method returns a new String object as a result of replacing all the occurrences of regex pattern with the replacement method argument.

Compatibility Version :

Requires Java 1.4 and up

Exception :

PatternSyntaxException

This exception will be thrown if and only if the regex pattern is invalid

Discussion :

The regex string declared as a parameter on method replaceAll() will serve as a searching pattern in replacing all the occurrences of our String replacement.

Be aware that in using the method replaceAll will not make our String change its value. Once a String has been instantiated, it’s no longer changeable. Thus, if we want to use the new String object what we can do is to reassign it again to our String object or create a new String object.

Let’s take for example:

What would you expect to be printed on the console? Would it be “x234x23” or “1234124”? As we have said earlier, invoking the replaceAll method will not change the String object exampleString, rather it will create a new String object.

Java Code Example :

This example source code demonstrates the use of replaceAll method of String class. This is a simple replacement of all the occurrences of String “0” to “**”.

Sample Output :

Running the replaceAll() method example source code of [class name here] class will give you the following output

java string replaceall method example

java string replaceall method example

Exception Scenario :

Suggested Reading List :