STRING INSTANCE METHODS

Java String replaceAll() method

replaceAll() finds every part of a string that matches a regular expression and replaces it with the specified text. The method returns a String value, while the original text stays unchanged. A regular expression is also called a regex.

Replacing all digit sequences

String tekstas = "Java1 Java22";

String rezultatas = tekstas.replaceAll("[0-9]+", "#");

System.out.println(rezultatas);
Console output

Java# Java#

  1. The variable tekstas stores the text Java1 Java22.
  2. The first argument "[0-9]+" is a regex: [0-9] means one digit from 0 to 9, and + means one or more consecutive occurrences.
  3. The second argument "#" is the replacement text. Each match is replaced with one #.
  4. There are two matches: 1 and 22. The second match covers both digits, producing Java# Java#.

replaceAll() searches for matches within the string; the whole string does not have to match the regex. This differs from matches(), which tests the entire string.

Why is replaceAll() an instance method?

replaceAll() is called on the string to search and transform. Its arguments supply the search rule and replacement text.

String rezultatas = tekstas.replaceAll("[0-9]+", "#");

We do not write String.replaceAll(...), because this is not a static method. The receiver is tekstas, and the regex and replacement are supplied inside the parentheses.

Method syntax

public String replaceAll(String regex, String replacement)

Parts of the replaceAll() method
PartMeaning
regexThe search rule, supplied as a String. It can contain special regex symbols.
replacementThe replacement text, also a String. Dollar signs and backslashes have special roles in it.
Return typeString – the text after replacement.
Possible errorsPatternSyntaxException for an invalid regex; other errors may arise from an invalid group reference or null values can also cause an exception.
Java versionThe method is available since Java 1.4.

The parameter names regex and replacement come from the Java API. The first describes what to find; the second describes what to substitute for each match. Both arguments are strings, so we use double quotes.

Regex elements used in these examples

Meanings of the search rules
Regex elementMeaning
[0-9]One digit from 0 to 9.
[0-9]+One or more consecutive digits.
\s+One or more spaces, tabs, or other whitespace characters recognized by this regex class.
.Any character except line terminators under the default rules.
[A-Z]{2}Exactly two uppercase Latin letters.
( ... )A group that captures the matching part of the string.

The regex \s+ is written as "\\s+" in a Java string literal: two backslashes in Java source preserve one backslash in the string. By default, this regex class does not cover all Unicode whitespace characters.

replaceAll() does not change the original string

String tekstas = "Java1";

tekstas.replaceAll("[0-9]", "#");
System.out.println(tekstas);

tekstas = tekstas.replaceAll("[0-9]", "#");
System.out.println(tekstas);
Console output

Java1
Java#

String is immutable. We leave the first result unassigned, so the variable still stores Java1. Saving the second result gives us Java#.

The regex dot and searching for a literal dot

String tekstas = "a.b.c";

System.out.println(tekstas.replaceAll(".", "-"));
System.out.println(tekstas.replaceAll("\\.", "-"));
Console output

-----
a-b-c

  1. In the first call, "." is a regex, so it matches each of the five characters in this string. The result is -----.
  2. The regex for a literal dot is \.. The backslash removes the dot’s special meaning.
  3. In Java source, this regex is written as "\\.". Only the two dots match, producing a-b-c.

Practical example: normalizing repeated whitespace

String tekstas = "  Java   Quest  ";

String rezultatas = tekstas.replaceAll("\\s+", " ").trim();

System.out.println("[" + rezultatas + "]");
Console output

[Java Quest]

  1. "\\s+" finds each run of whitespace. Here, those are runs of two, three, and two spaces.
  2. The replacement " " contains one space, so each matched run becomes a single space.
  3. After replacement, one space remains at each end. trim() removes these spaces.
  4. The square brackets make the result visible: [Java Quest]. They are added only when printing.

Removing several different separators

String kodas = "JA-VA_QUEST 2026";

System.out.println(kodas.replaceAll("[-_ ]", ""));
Console output

JAVAQUEST2026

The character class [-_ ] matches one of three characters: a hyphen, an underscore, or an ordinary space. The hyphen is placed first in the class, so it does not define a range here.

The replacement "" is empty, so the matched character is removed. A single call removes all three kinds of separators.

Case sensitivity and the (?i) flag

String tekstas = "Java java JAVA";

System.out.println(tekstas.replaceAll("Java", "Kotlin"));
System.out.println(tekstas.replaceAll("(?i)Java", "Kotlin"));
Console output

Kotlin java JAVA
Kotlin Kotlin Kotlin

Matching is case-sensitive by default: the first call matches only Java. The flag (?i) in the second regex enables case-insensitive matching for these Latin letters, so all three parts are replaced.

The flag belongs to the search pattern. It does not change the case of the replacement text or automatically provide comparison rules for every language.

Reusing captured parts with $1 and $2

String kodai = "LT-123 EE-456";

String rezultatas = kodai.replaceAll("([A-Z]{2})-([0-9]{3})", "$2/$1");

System.out.println(rezultatas);
Console output

123/LT 456/EE

  1. The first pair of parentheses, ([A-Z]{2}), captures two uppercase letters. This is group 1. In the first code, its value is LT.
  2. The hyphen between the groups matches a literal hyphen. The second group, ([0-9]{3}), captures three digits; in the first code, that is 123.
  3. In the replacement, $2 refers to the second group’s content, and $1 refers to the first group’s content. The slash between them is inserted literally.
  4. Thus LT-123 becomes 123/LT. The same rule is applied to the second code, giving 456/EE.

Groups are numbered by their opening parentheses, starting at 1. Newly inserted text is not processed again in this example: replacement uses non-overlapping matches in the original string.

Inserting a literal dollar sign: Matcher.quoteReplacement()

import java.util.regex.Matcher;

String tekstas = "price price";
String naujas = "$5";

String rezultatas = tekstas.replaceAll("price", Matcher.quoteReplacement(naujas));

System.out.println(rezultatas);
Console output

$5 $5

  1. The original text price price contains two words. The regex "price" finds each of them.
  2. The variable naujas stores the string "$5". It contains two characters: a dollar sign and the digit 5.
  3. Normally, $5 in replacement text would refer to the fifth regex group. This regex has no capturing groups, and we want the actual characters in the output.
  4. Matcher.quoteReplacement(naujas) prepares the value so that the dollar sign is inserted as an ordinary character. It does not modify the variable; its returned value is passed to the replacement operation.
  5. Both price matches are replaced, so the console displays $5 $5 without quotes. The space between the words remains.

Matcher.quoteReplacement() also handles backslashes in replacement text literally. The import lets us use the class name Matcher.

When the search text contains regex symbols

import java.util.regex.Pattern;

String tekstas = "java.quest.lt";
String ieskoma = ".";

System.out.println(tekstas.replaceAll(Pattern.quote(ieskoma), "-"));
Console output

java-quest-lt

Pattern.quote(ieskoma) prepares the search text as a literal sequence. The dot is treated as an actual dot, so only the two dots are replaced.

Keep the roles distinct: Pattern.quote() is applied to the search pattern, while Matcher.quoteReplacement() is applied to replacement text. If both values are literal text and no regex is needed, it is simpler to use replace().

Differences between replaceAll(), replace(), and replaceFirst()

String tekstas = "Java Java";

System.out.println(tekstas.replace("Java", "Kotlin"));
System.out.println(tekstas.replaceAll("Java", "Kotlin"));
System.out.println(tekstas.replaceFirst("Java", "Kotlin"));
Console output

Kotlin Kotlin
Kotlin Kotlin
Kotlin Java

Choosing a replacement method
MethodBehavior
replace()Replaces all literal matches. Search and replacement text are not interpreted as regex syntax.
replaceAll()Replaces all regex matches; replacement text can reference captured groups.
replaceFirst()Replaces only the first regex match; replacement-text rules are the same.

The first two results match here because the word Java contains no special regex symbols. The dot example showed why other inputs can produce different results.

replace() · matches()

No matches, an empty string, and an empty regex

System.out.println("Java".replaceAll("[0-9]+", "#"));
System.out.println("[" + "".replaceAll("[0-9]+", "#") + "]");
System.out.println("ab".replaceAll("", "-"));
Console output

Java
[]
-a-b-

If the regex finds no matches, the text content stays unchanged. The first call has no digits to match. The empty string in the second call has no digits either, so nothing appears between the brackets.

An empty regex "" can match without consuming a character. In this example, matches occur before a, between the letters, and after b, so three hyphens are inserted. This differs from empty replacement text, which removes matches.

An invalid regex throws PatternSyntaxException

String tekstas = "Java123";

System.out.println(tekstas.replaceAll("[0-9", "#"));
Result

PatternSyntaxException

The expression [0-9 starts a character class but omits the closing bracket. Java cannot compile the regex and throws PatternSyntaxException before replacement.

A valid regex that finds nothing is not an error. The preceding example with a digit-free string demonstrated that case.

A reference to a group that does not exist

System.out.println("price".replaceAll("price", "$5"));
Result

IndexOutOfBoundsException

The search finds the word price, then Java tries to prepare its replacement. The value $5 requests the fifth group’s content, but the regex "price" has no such group. This call therefore throws IndexOutOfBoundsException.

To insert an actual dollar sign, use the earlier Matcher.quoteReplacement() example. A group reference is appropriate when that group is actually defined in the regex.

Regex and string references must not be null

String tekstas = "Java";
String regex = null;

System.out.println(tekstas.replaceAll(regex, "Kotlin"));
Result

NullPointerException

The regex value here is null, so Java has no search rule and throws NullPointerException. An empty regex "" is an actual string and behaves differently.

The method cannot be called on a null string reference either. Supply valid, non-null replacement text too; an empty string can remove matching parts.

Common mistakes

  • Leaving the value returned by replaceAll() unassigned.
  • Treating a dot or another regex symbol as ordinary search text.
  • Forgetting to double the backslash in Java source, for example in "\\s+".
  • Treating $1 in replacement text as just a dollar sign and a digit, even though it is a group reference.
  • Expecting the method to replace only the first match or to modify the original object.
  • Expecting unchanged text for an invalid regex, even though the call throws an exception.

When should you use replaceAll()?

Use replaceAll() when a rule describes the parts to replace: digit sequences, repeated whitespace, several separator types, or structured codes. For literal replacement, use replace(); for only the first regex match, use replaceFirst().

If the same regex is applied to many strings, you can create a Pattern once with Pattern.compile() and use its matcher(...).replaceAll(...) for each string. This reuses the compiled search pattern.