Java String.replaceFirst
Replace only the first part of the input matching a regular expression.
A simple example
String.replaceFirst
- Start with "a1b2"
- Do this Replace only the first digit with *
- Result "a*b2"
class Main {
public static void main(String[] args) throws Exception {
System.out.println("a1b2".replaceFirst("[0-9]", "*"));
}
}
a*b2
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.javaUpdate 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.
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"));
}
}
Gate 7, Gate 4
The later stop is preserved after the first match is replaced.
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.
class Main {
public static void main(String[] args) throws Exception {
String file = "copy-copy-bill";
System.out.println(file.replaceFirst("^copy-", ""));
}
}
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.
What to watch for
The replacement string recognizes group references. Quote user-provided replacement text with Matcher.quoteReplacement.