Java replaceAll - yuriyni.com

Java replaceAll. Tutorial and Examples

What is a replaceAll?

The java indexOf() method of String class is used for getting a substring from the string.

public final class String extends Object implements Serializable, Comparable<String>, CharSequence, Constable, ConstantDesc

...

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Beginning with JDK 9, all of java.lang is part of the java.base module. The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Java Platform, Standard Edition & Java Development Kit Version 16 API Specification
Module java.base
Package java.lang
Class String

Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or StringBuilder, or use a String method that constructs a new copy of the string with your modifications complete.

Syntax #1 of String replaceAll() method

public String replaceAll​(String regex, String replacement)

The Java String replaceAll() returns a string after it replaces each substring of that matches the given regular expression with the given replacement.

Parameters:

regex – the regular expression to which this string is to be matched

replacement – the string to be substituted for each match

String replaceAll Example #1

package com.yuriyni.java.base.java.lang;

public class ReplaceAllDemo {
    public static void main(String[] args) {

        String str1 = "aabbaaac";
        String str2 = "Hello557World223";

        // regex for sequence of digits
        String regex = "\\d+";

        // all occurrences of "aa" is replaceAll with "zz"
        System.out.println(str1.replaceAll("aa", "vv")); // zzbbzzac

        // replace a digit or sequence of digits with a whitespace
        System.out.println(str2.replaceAll(regex, " ")); // Learn Java @
    }
}

Output

vvbbvvac
Hello World 

Download source code

https://github.com/yuriynee/learning-java-with-yuriy-ni