w3resource

Java String: replaceAll() Method

public String replaceAll(String regex, String replacement)

The replaceAll() method replaces each substring of this string that matches the given regular expression with the given replacement.

An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

Pattern.compile(regex).matcher(str).replaceAll(repl)

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

Java Platform: Java SE 8

Syntax:

replaceAll(String regex, String replacement)

Parameters:

Name Description Type
regex the regular expression to which this string is to be matched String
replacement the string to be substituted for each match String

Return Value:The resulting String

Return Value Type: String

Pictorial presentation of Java String replaceAll() Method

Java String: replaceAll() Method

Example: Java String replaceAll(String regex, String replacement) Method

The following example shows the usage of java String() method.

public class StringReplaceAllExample {

    public static void main(String[] args) {
        // Declare the source string
        String stringVal = "10010011";
        // Define the regex pattern
        String regex = "0";
        // Replacing all the occurrences of String "0"
        String objStr = stringVal.replaceAll("0", "*");
        System.out.println();
        System.out.println("Original String Object: "+stringVal);
        System.out.println("New String Object: "+objStr);
        System.out.println();
    }

}

Output:

Original String Object: 10010011                       
New String Object: 1**1**11

Java Code Editor :

Previous:replace Method
Next:replaceFirst Method



Follow us on Facebook and Twitter for latest update.