Library contents

Java String.replaceFirst

Replace only the first part of the input matching a regular expression.

A simple example

String.replaceFirst

  1. Start with "a1b2"
  2. Do this Replace only the first digit with *
  3. Result "a*b2"
The search stops replacing after the 1. The final 2 remains.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("a1b2".replaceFirst("[0-9]", "*"));
    }
}
Output
a*b2

Syntax

Java syntax
public String replaceFirst(String regex, String replacement)
JDK 21 method signatures (1)
public String replaceFirst(String regex, String replacement)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Update the first stop on a route

A transit editor changes selected text in a route while preserving its remaining stops or punctuation. Identify which occurrences belong to the requested edit before rebuilding the public route label.

From the programString route = "Gate 4, Gate 4"
ResultGate 7, Gate 4
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String route = "Gate 4, Gate 4";
        System.out.println(route.replaceFirst("Gate [0-9]+", "Gate 7"));
    }
}
Output
Gate 7, Gate 4

The later stop is preserved after the first match is replaced.

Advertisements

Remove a receipt prefix only at the start

A printed scanner code may begin with a standard prefix. Remove it only under the intended matching rule so the same letters inside the actual identifier are preserved.

From the programString file = "copy-copy-bill"
Resultcopy-bill
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String file = "copy-copy-bill";
        System.out.println(file.replaceFirst("^copy-", ""));
    }
}
Output
copy-bill

The anchor limits the match to the beginning and only one prefix is removed.

Mask a public job number

A noticeboard shows the department prefix and hides the serial. The editor replaces a matching run of digits with a single star before sharing the label. Each sample has one numeric run.

GivenART-184 → replace digits
Worked resultART-*

What to watch for

The replacement string recognizes group references. Quote user-provided replacement text with Matcher.quoteReplacement.

Documentation for String.replaceFirst