STRING INSTANCE METHODS

Java String replaceFirst() method

replaceFirst() replaces the first part of a string that matches a regular expression, also called a regex. Later matches stay unchanged. The method returns a String value and leaves the original text unchanged.

Replacing only the first match

String tekstas = "Java Quest, Java notes";

String rezultatas = tekstas.replaceFirst("Java", "Kotlin");

System.out.println(rezultatas);
Console output

Kotlin Quest, Java notes

  1. The variable tekstas stores the text Java Quest, Java notes.
  2. The first argument "Java" is the search pattern. This regex has no special symbols, so it searches for that exact four-letter sequence.
  3. The second argument "Kotlin" supplies the text that replaces the first match.
  4. Searching proceeds from left to right. The first Java is replaced, while the second Java stays the same.

Why is replaceFirst() an instance method?

replaceFirst() is called on the string to search. Its arguments specify the pattern to find and the text to substitute.

String rezultatas = tekstas.replaceFirst("Java", "Kotlin");

We do not write String.replaceFirst(...), because this method is not static. Below, we compare it with Matcher.replaceFirst(), where the regex has already been prepared.

Method syntax

public String replaceFirst(String regex, String replacement)

Parts of the replaceFirst() method
PartMeaning
regexThe search rule, supplied as a String.
replacementThe replacement text, also a String. It can reference captured regex groups.
Return typeString – the text after replacing the first match.
Possible errorsPatternSyntaxException for an invalid regex; other errors may arise from an invalid group reference or null.
Java versionThe method is available since Java 1.4.

The parameter regex describes the match to find, while replacement describes its substitution. These are Java API parameter names. Both arguments are strings and use double quotes.

The first match can be a whole number

String tekstas = "id=17; next=2026";

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

id=#; next=2026

  1. [0-9] matches one digit from 0 to 9. The quantifier + allows one or more consecutive digits in a match.
  2. The first digit sequence found is 17. The entire sequence is replaced with one #.
  3. The later sequence 2026 is left unchanged. The method replaces one match, which can contain several characters.

The match does not have to start at the beginning of the string. Here, the first three characters do not match the regex and remain in the result.

replaceFirst() does not change the original string

String tekstas = "Java Java";

tekstas.replaceFirst("Java", "Kotlin");
System.out.println(tekstas);

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

Java Java
Kotlin Java

String is immutable. We do not save the first result, so the variable still stores Java Java. Assigning the second result to the variable gives us Kotlin Java.

Practical example: removing a prefix

String tekstas = "draft: Java draft: notes";

System.out.println(tekstas.replaceFirst("^draft: ", ""));
System.out.println("Java draft: notes".replaceFirst("^draft: ", ""));
Console output

Java draft: notes
Java draft: notes

  1. The regex "^draft: " begins with ^, which means the start of the whole string when no additional flags are used. The pattern also includes a space after the colon.
  2. The replacement "" is empty, so the initial prefix is removed.
  3. The sequence draft: in the middle remains. The second string has no such prefix at all, so it stays unchanged.

Without ^, the first match could also occur in the middle of the string. Add this anchor when the beginning position matters.

The dot and backslashes in Java source

String tekstas = "java.quest.lt";

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

-ava.quest.lt
java-quest.lt

  1. The regex "." matches one character other than line terminators by default. The first character here is j, so it is replaced with a hyphen.
  2. The regex for an actual dot is \.. In Java source it is written as "\\.", because two source backslashes preserve one backslash in the string.
  3. The second call replaces only the first dot. The second dot remains, producing java-quest.lt.

If search text comes from a variable and should be treated literally, you can prepare the search pattern with Pattern.quote().

Why can the first match cover the whole string?

String tekstas = "Java Quest Java Notes";

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

Kotlin Quest Java Notes
Kotlin

The first regex describes only the four letters Java. The second includes .*: the dot matches a character, and the star allows zero or more repetitions. This string contains no line terminators.

By default, the star takes as much matching text as possible. The first match of the second pattern therefore covers the entire string and is replaced by Kotlin. Only one match has been replaced.

Case sensitivity and the position of the first match

String tekstas = "java Java JAVA";

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

java Kotlin JAVA
Kotlin Java JAVA

The first call is case-sensitive, so the first matching word is Java in the middle. The flag (?i) in the second regex ignores case for these Latin letters, so the first match becomes the initial java.

Both calls replace only one match. Ignoring case here leaves the rest of the string intact and does not automatically supply comparison rules for every language.

Reordering the first code with $1 and $2

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

System.out.println(kodai.replaceFirst("([A-Z]{2})-([0-9]{3})", "$2/$1"));
Console output

123/LT EE-456

  1. The group ([A-Z]{2}) captures two uppercase Latin letters; in the first match, that is LT. This is the first group.
  2. The group ([0-9]{3}) captures three digits; in the first match, that is 123. This is the second group. The hyphen between the groups matches a literal hyphen.
  3. In replacement text, $2 inserts the second group’s content, while $1 inserts the first group’s content. A literal slash is placed between them.
  4. The first code becomes 123/LT, while the second code EE-456 stays unchanged.

How do you replace the first match with $5?

import java.util.regex.Matcher;

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

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

System.out.println(rezultatas);
Console output

$5 price

  1. In the string price price, the regex "price" first finds the initial word.
  2. The variable naujas stores two characters: a dollar sign and the digit 5. We want to insert both literally.
  3. Matcher.quoteReplacement(naujas) prepares the text so that $5 is not interpreted as a reference to the fifth regex group. It also suppresses the special meaning of backslashes in replacement text.
  4. Only the first price is replaced. The console displays $5 price without quotes, and the second word stays unchanged.

Here, the class is imported only to call its static helper. Replacement itself is still performed on a String object.

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

String tekstas = "Java Java";

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

Kotlin Java
Kotlin Kotlin
Kotlin Kotlin

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

The last two results are identical here because Java contains no special regex symbols. A plain word in a regex does not automatically require word boundaries: it can match inside a longer word too.

replaceAll() · replace()

Relationship to Matcher.replaceFirst()

import java.util.regex.Pattern;
import java.util.regex.Matcher;

String tekstas = "id=17; next=2026";
Pattern taisykle = Pattern.compile("[0-9]+");
Matcher paieska = taisykle.matcher(tekstas);

System.out.println(tekstas.replaceFirst("[0-9]+", "#"));
System.out.println(paieska.replaceFirst("#"));
System.out.println(paieska.replaceFirst("#"));
Console output

id=#; next=2026
id=#; next=2026
id=#; next=2026

  1. Pattern.compile("[0-9]+") compiles the regex and returns a pattern object.
  2. taisykle.matcher(tekstas) associates the pattern with a specific string, creating a Matcher object.
  3. String.replaceFirst() receives two arguments: the regex and the replacement. This overload of Matcher.replaceFirst() receives only the replacement, because its regex and input are already associated.
  4. Calling paieska.replaceFirst("#") again restarts the search. It replaces 17 again rather than moving to the next number.

Both approaches return the same text here. A separately compiled Pattern is useful when the same rule needs to be applied to several strings.

public String replaceFirst(String replacement)

This is the signature of this Matcher overload. Keep it distinct from the two-argument String method shown earlier.

No matches, an empty string, and an empty regex

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

Java
[]
-ab

The first string has no digits, so its content stays the same. The empty string in the second call has no word to match, so nothing is printed between the brackets.

An empty regex "" can match without consuming characters. The first such match is at the start, so one hyphen is inserted, producing -ab. This differs from an empty replacement string, which removes the matched part.

An invalid regex throws PatternSyntaxException

String tekstas = "Java17";

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

PatternSyntaxException

The expression [0-9 is missing its closing bracket. Java cannot compile this pattern and throws PatternSyntaxException. A valid regex with no matches would simply leave the content unchanged.

A reference to a group that does not exist

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

IndexOutOfBoundsException

The first word price is found, but the replacement $5 requests the fifth regex group. The pattern "price" has no such group, so this call throws IndexOutOfBoundsException.

For literal characters, use the earlier Matcher.quoteReplacement() example. Use a group reference when you want to reuse text captured by the regex.

Regex and string references must not be null

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

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

NullPointerException

The search pattern here is null, so the call throws NullPointerException. This differs from an empty regex "", whose behavior we saw earlier.

The method cannot be called on a null string reference either. Supply a valid string as replacement; an empty string can remove the matched text.

Common mistakes

  • Expecting replaceFirst() to replace just one character even though the regex can match a longer sequence.
  • Confusing the first match with the first word or with the start of the string.
  • Forgetting to assign the returned string.
  • Treating the dot as a literal character or failing to double the backslash in the Java string "\\.".
  • Treating $1 as ordinary replacement text even though it references a capturing group.
  • The method Matcher.replaceFirst() is given an extra regex argument even though its pattern is already prepared.

When should you use replaceFirst()?

Use replaceFirst() when only the first matching part should change: the first code, first number, initial prefix, or first marker. The regex defines the match, so check both its extent and its position.

To replace all regex matches, use replaceAll(). For literal replacement throughout the string without regex rules, use replace().