Java Tutorial Java Advanced Java References

Java String - replaceAll() Method



The Java replaceAll() method returns the string with all occurrences of the specified regular expression replaced with specified string in the given string.

Syntax

public String replaceAll(String regex, String replacement)

Parameters

regex specify the regular expression to which this string is to be matched.
replacement specify the string to be substituted for each match.

Return Value

Returns the replaced version of the specified string.

Exception

Throws PatternSyntaxException, if the regular expression's syntax is invalid.

Example:

In the example below, replaceAll() method returns the string where all occurrences of the specified regular expression are replaced with specified string in the given string called MyString.

public class MyClass {
  public static void main(String[] args) {
    String MyString = "Hello World!";
    
    //l is replaced with k
    String NewString1 = MyString.replaceAll("l", "k");
    //printing new string
    System.out.println(NewString1);

    //ll is replaced with kk
    String NewString2 = MyString.replaceAll("ll", "kk");
    //printing new string
    System.out.println(NewString2);
  }
}

The output of the above code will be:

Hekko Workd!
Hekko World!

❮ Java String Methods