In this Java tutorial, you will learn how to replace all occurrences of a substring in a string. We shall use String.replaceAll() for regex-based replacement, compare it with String.replace() for literal substring replacement, and cover common cases such as removing a substring and handling regex special characters.

Java replaceAll() to replace all occurrences of a substring

To replace all occurrences of an old string with a replacement string, you can use the String.replaceAll() method.

There is one important detail: the first argument of replaceAll() is a regular expression, not a plain literal substring. For simple words such as "Good", the result is usually the same as a literal replacement. For strings that contain characters such as ., +, *, ?, [, or (, you should either escape the regex or use Pattern.quote().

Strings in Java are immutable. The original string is not modified; replaceAll() returns a new string with the replacements applied.

The syntax of String.replaceAll() is given below.

</>
Copy
 public String replaceAll(String regex, String replacement)

For regex, provide the pattern that should be matched in the source string. For a normal word or simple substring, this may look like the old string you want to replace. For regex-based matching, you can use a regular expression such as "\s+" to match one or more whitespace characters.

For replacement, provide the new text that should be inserted for every match.

Part of replaceAll()What it means in Java substring replacement
regexThe regular expression to search for in the string.
replacementThe text used in place of each match.
Return valueA new String after replacing all matches.
Original stringUnchanged, because Java strings are immutable.

You can refer to the official Java String API documentation for the complete method contract.

Java replaceAll() examples for every matching substring

1. Java replaceAll() example that replaces every matching word

In this example, we shall take three strings: str1, old_string, and new_string. We shall try to replace all the occurrences of the string old_string with new_string in str1.

Example.java

</>
Copy
public class Example { 
    public static void main(String[] args) {
        String str1 = "Hi! Good morning. Have a Good day.";
        String old_string = "Good";
        String new_string = "Very-Good";

        //replace all occurrences
        String resultStr = str1.replaceAll(old_string, new_string);
        System.out.println(resultStr);
    }
}

Run the above Java program in console or your favorite IDE, and you shall see an output similar to the following.

Output

Hi! Very-Good morning. Have a Very-Good day.

All occurrences of "Good" are replaced with "Very-Good". The first "Good" and the second "Good" are both changed.

2. Java replaceAll() when the substring is not found

In this example, we shall take three strings: str1, old_string, and new_string. We shall try to replace all the occurrences of the string old_string with new_string in str1. But old_string is not present in str1.

Example.java

</>
Copy
public class Example { 
    public static void main(String[] args) {
        String str1 = "Hi! Good morning. Have a Good day.";
        String old_string = "Bad";
        String new_string = "Very-Good";

        //replace all occurrences
        String resultStr = str1.replaceAll(old_string, new_string);
        System.out.println(resultStr);
    }
}

Run the above program.

Output

Hi! Good morning. Have a Good day.

Since the old_string is not present in str1, replaceAll() returns a string with the same content as str1.

3. Remove all occurrences of a substring using Java replaceAll()

To remove all occurrences of a substring, use an empty string as the replacement. The following program removes every occurrence of "red " from the sentence.

Example.java

</>
Copy
public class Example {
    public static void main(String[] args) {
        String str = "red apple, red rose, red car";

        String result = str.replaceAll("red ", "");

        System.out.println(result);
    }
}

Output

apple, rose, car

This is useful when you want to delete repeated tokens, prefixes, or words from a string. If the text you are removing comes from user input, prefer Pattern.quote() as shown in the next example.

4. Replace all literal substring matches that contain regex special characters

Because replaceAll() accepts a regex, some characters do not mean themselves. For example, + is a regex quantifier. If your old substring is a literal plus sign, quote it with Pattern.quote().

Example.java

</>
Copy
import java.util.regex.Pattern;

public class Example {
    public static void main(String[] args) {
        String str = "a+b+c+";
        String oldString = "+";
        String newString = "-";

        String result = str.replaceAll(Pattern.quote(oldString), newString);

        System.out.println(result);
    }
}

Output

a-b-c-

Pattern.quote(oldString) tells Java to treat the old substring as normal text, not as a regex pattern.

5. Replace all occurrences without regex using Java String.replace()

If you want literal substring replacement and do not need regex matching, String.replace() is often the clearer choice. It replaces all occurrences of the target character sequence, but it does not treat the target as a regex.

Example.java

</>
Copy
public class Example {
    public static void main(String[] args) {
        String str = "www.example.com";

        String result = str.replace(".", "-");

        System.out.println(result);
    }
}

Output

www-example-com

Here "." is treated as a literal dot. If you used replaceAll(".", "-"), the dot would act as a regex that matches almost every character, and the result would not be the same.

6. Escape replacement text that contains dollar signs or backslashes

The replacement string in replaceAll() also has special handling for $ and backslash characters. If the replacement text is literal and may contain these characters, use Matcher.quoteReplacement().

Example.java

</>
Copy
import java.util.regex.Matcher;

public class Example {
    public static void main(String[] args) {
        String str = "Order ID: 123";

        String result = str.replaceAll("\\d+", Matcher.quoteReplacement("$NUMBER"));

        System.out.println(result);
    }
}

Output

Order ID: $NUMBER

In this example, "\\d+" matches one or more digits. Matcher.quoteReplacement("$NUMBER") inserts $NUMBER as plain text.

Java replaceAll() versus replace() versus replaceFirst()

Java provides more than one method for replacing text in a string. Choose the method based on whether you need regex matching and whether you want to replace all matches or only the first match.

MethodPattern typeHow many matches are replaced?Use this when
replaceAll(regex, replacement)RegexAll matchesYou need pattern-based matching, such as digits, whitespace, or case-insensitive patterns.
replace(target, replacement)Literal text or characterAll matchesYou want to replace a normal substring exactly as written.
replaceFirst(regex, replacement)RegexFirst match onlyYou want to change only the first regex match.

For most plain substring replacement tasks, replace() is easier to read. Use replaceAll() when regex matching is required.

Case-sensitive and case-insensitive Java substring replacement

replaceAll() is case-sensitive by default. In the first example, "Good" matches "Good", but it would not match "good" or "GOOD".

For case-insensitive replacement, you can use the regex flag (?i) before the pattern.

Example.java

</>
Copy
public class Example {
    public static void main(String[] args) {
        String str = "Good morning. good evening. GOOD night.";

        String result = str.replaceAll("(?i)good", "Nice");

        System.out.println(result);
    }
}

Output

Nice morning. Nice evening. Nice night.

The pattern "(?i)good" matches Good, good, and GOOD.

Common mistakes while replacing all occurrences in a Java string

  • Using replaceAll() for literal text that contains regex symbols: Use replace() or Pattern.quote() when the old substring is plain text.
  • Expecting the original string to change: Assign the returned value to a variable because strings are immutable.
  • Using replaceFirst() by mistake: replaceFirst() changes only the first match, while replaceAll() changes every regex match.
  • Forgetting that matching is case-sensitive: Use a case-insensitive regex when "Good", "good", and "GOOD" should all match.
  • Putting unescaped $ in replacement text: Use Matcher.quoteReplacement() when replacement text contains special replacement characters.

FAQs on Java replaceAll() for all substring occurrences

Does Java replaceAll() replace literal substrings or regex matches?

replaceAll() replaces regex matches. If the substring is simple text such as "Good", it behaves like a normal substring replacement. If the substring contains regex special characters, use Pattern.quote() or use String.replace() for literal replacement.

How do I replace all occurrences of a string in Java without regex?

Use String.replace(target, replacement). It replaces all literal occurrences of the target character sequence without treating the target as a regular expression.

How can I remove all occurrences of a substring in Java?

Use an empty replacement string. For example, str.replaceAll("red ", "") removes every regex match of "red ". For literal user-entered text, use str.replace(oldText, "") or quote the regex with Pattern.quote(oldText).

Why does replaceAll(“.”, “-“) replace every character in Java?

In regex, a dot matches almost any single character. Since replaceAll() uses regex, "." is not treated as a literal dot. Use replace(".", "-") or replaceAll("\\.", "-") to replace literal dots.

Does replaceAll() modify the original Java string?

No. Java strings are immutable. replaceAll() returns a new string. Store the return value in a variable if you want to use the changed text.

Editorial QA checklist for Java substring replacement tutorials

  • Confirm that the article says replaceAll() uses regex, not plain literal matching.
  • Check that examples show all occurrences being replaced, not only the first occurrence.
  • Verify output blocks exactly match the Java code above them.
  • Include a safe option for literal substrings containing ., +, or other regex characters.
  • Mention that the original string is unchanged and the returned string must be used.
  • Use Matcher.quoteReplacement() when the replacement text contains $ or backslashes.

Summary of replacing all occurrences of a substring in Java

In this Java Tutorial, we have learned how to replace all occurrences of a substring in a string using String.replaceAll(). We also saw when String.replace() is better for literal substring replacement, how to remove all occurrences with an empty replacement, and how to handle regex special characters safely.