Java String replaceFirst() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
String

Definition

In Java, replaceFirst(regex, replacement) returns a new String in which only the first part of the text that matches the regular expression is replaced. Everything after that first match is copied unchanged.

It follows the same rules as replaceAll: the first argument is a regex, and the replacement can use $1-style group references. Use it for "change the first one" jobs such as stripping a prefix or numbering the first item.

replaceFirst() is an instance method of java.lang.String, added in Java 1.4. Call it on a string, as in text.replaceFirst(...); calling it on a null reference throws NullPointerException. Strings are immutable, so it never changes the original: it returns a new String (or the same one when nothing changes). Keep the result.

Syntax

Pass a regex and a replacement text.

java
String once   = text.replaceFirst("one", "1");
String noZero = code.replaceFirst("^0+(?!$)", "");
CallWhat it does
"aaa".replaceFirst("a", "b")"baa".
"x1y2".replaceFirst("\\d", "#")"x#y2".
"abc".replaceFirst("z", "!")"abc": no match, same text.

Because the pattern is a regex, a dot matches any character. To replace the first literal period, escape it as "\\.", or quote the whole text with Pattern.quote(text).

Library declarations
java
public String replaceFirst(String regex, String replacement);

Parameters

ParameterDescription
regexThe regular expression to search for.
replacementText for the first match; $n inserts group n.

Return Value

Return ValueDescription
StringThe text with the first match replaced, or the same text when nothing matches.

Java Examples

Example 1 — replaceFirst() Next to replaceAll()

The same pattern, one call that stops after the first match and one that does not.

java
public class ReplaceFirstVsAll {
    public static void main(String[] args) {
        String text = "one one two one";

        System.out.println(text.replaceFirst("one", "1"));
        System.out.println(text.replaceAll("one", "1"));
        System.out.println("Order #12 of 40".replaceFirst("\\d+", "N"));
    }
}

How It Works

  1. Only the first match. replaceFirst changes the leading "one" and copies the rest of the sentence as it was.
  2. Every match. replaceAll with the same arguments replaces all three occurrences.
  3. A regex for numbers. The pattern \d+ first matches "12"; the later "40" is never touched.

Example 2 — Strip Leading Zeros but Keep a Single 0

An anchored pattern with a lookahead handles all the edge cases.

java
public class ReplaceFirstZeros {
    public static void main(String[] args) {
        String[] codes = {"000420", "0", "007", "1200"};

        for (String c : codes) {
            System.out.println(c + " -> " + c.replaceFirst("^0+(?!$)", ""));
        }
    }
}

How It Works

  1. Anchor at the start. ^0+ only matches zeros at the very beginning, so the zeros inside "1200" are safe.
  2. Never remove everything. The lookahead (?!$) forbids the match from reaching the end, so "0" stays "0".
  3. One match is enough. The leading zeros form a single run, so replacing the first match with "" cleans "000420" to "420".

Example 3 — A Dot, an Escaped Dot, and a Group

See how the regex syntax changes what "first match" means.

java
public class ReplaceFirstDot {
    public static void main(String[] args) {
        String version = "a.b.c";

        System.out.println(version.replaceFirst(".", "X"));
        System.out.println(version.replaceFirst("\\.", "X"));
        System.out.println("x-y-z".replaceFirst("-(.)", "+$1"));
    }
}

How It Works

  1. An unescaped dot is a wildcard. "." matches any character, so the first match is the letter a.
  2. Escape for a real period. "\\." matches only a period; the first one sits between a and b.
  3. Reuse the captured char. -(.) matches "-y" and captures the y; "+$1" writes it back after a plus sign.

Frequently Asked Questions

Use replaceFirst(regex, replacement). For literal text with special characters, pass Pattern.quote(text) as the regex.
Yes. That is why "." matches any character. Escape it as "\\." in Java source to match a period.
A string with the same content as the original. No exception is thrown.
Yes, exactly like replaceAll(): $1, $2, and so on insert the captured groups of the first match.
Both use regex. replaceFirst() stops after the first match, replaceAll() replaces every match.

Next: resolveConstantDesc()

Resolve the string as a constant descriptor: returns itself (Java 12+).

resolveConstantDesc() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful