The String.replaceFirst() method replaces the first substring of this string that matches a specified regular expression with a given replacement.
Single Occurrence Regex Substitution: Unlike replaceAll() which alters all matching sequences globally, replaceFirst() halts after substituting the very first match. For non-regex literal replacements, see replace(). To check whether a string begins with a prefix, explore startsWith(). For slicing without replacement, see substring().
The replaceFirst() method is defined in java.lang.String:
// Formal signature of String.replaceFirst() in java.lang.String
public String replaceFirst(String regex, String replacement)
| Parameter / Element | Type | Description & Operational Rule |
|---|---|---|
regex |
String |
The regular expression pattern to search for in the string. |
replacement |
String |
The replacement text substituted for the first match found. |
| Return Value | String |
A new String with the first matching substring replaced. |
| Exception | Runtime | Throws PatternSyntaxException if the regular expression syntax is malformed. |
Replacing only the first occurrence of an individual character or substring:
String str = "Welcome to plus2net.com";
// 1. Replace only the FIRST matching letter 'o' with an asterisk
System.out.println(str.replaceFirst("o", "*")); // Welc*me to plus2net.com
// 2. Replace only the FIRST occurrence of "com" with "net"
System.out.println(str.replaceFirst("com", "net")); // Welnete to plus2net.comTerminal Output:
Welc*me to plus2net.com
Welnete to plus2net.com
Contrasting single-match substitution against global replacements:
String sentence = "banana banana banana";
// 1. replaceFirst() replaces ONLY the first match
System.out.println("replaceFirst: " + sentence.replaceFirst("banana", "apple"));
// 2. replaceAll() replaces EVERY match via regex
System.out.println("replaceAll: " + sentence.replaceAll("banana", "apple"));
// 3. replace() replaces EVERY match literally without regex
System.out.println("replace: " + sentence.replace("banana", "apple"));Terminal Output:
replaceFirst: apple banana banana
replaceAll: apple apple apple
replace: apple apple apple
| Method | Search Pattern | Occurrences Replaced | Primary Use Case |
|---|---|---|---|
str.replaceFirst(...) |
Regular expression | First match only | Prefix stripping, leading zero removal, header normalization. |
str.replaceAll(...) |
Regular expression | All matches | Global pattern-based cleanup (all digits, all whitespace). |
str.replace(...) |
Literal sequence | All matches | Fast literal text replacement without regex parsing. |
Because the first argument is a regex, passing an unescaped dot . replaces the very first character of the string rather than a literal period:
String version = "v2.0.4";
// WRONG: In regex, '.' matches the very first character ('v')!
System.out.println("Unescaped dot: " + version.replaceFirst(".", "-")); // -2.0.4
// CORRECT: Escape the dot to target the first literal period
System.out.println("Escaped dot: " + version.replaceFirst("\\.", "-")); // v2-0.4Terminal Output:
Unescaped dot: -2.0.4
Escaped dot: v2-0.4
Using regular expression anchors to remove leading zeros while preserving standalone zeros:
String rawCode1 = "000452";
String rawCode2 = "00000";
// Strip leading zeroes: ^0+(?!$) removes leading zeros but preserves a single '0'
System.out.println("Normalized 1: " + rawCode1.replaceFirst("^0+(?!$)", "")); // 452
System.out.println("Normalized 2: " + rawCode2.replaceFirst("^0+(?!$)", "")); // 0Terminal Output:
Normalized 1: 452
Normalized 2: 0
Stripping leading http:// or https:// prefixes from web address strings using the start anchor ^:
String url1 = "https: // www.plus2net.com";
String url2 = "http: // plus2net.com/java";
// Strip leading http:// or https:// protocol header using regex anchor ^
String clean1 = url1.replaceFirst("^https?: // ", "");
String clean2 = url2.replaceFirst("^https?: // ", "");
System.out.println("Clean URL 1: " + clean1); // www.plus2net.com
System.out.println("Clean URL 2: " + clean2); // plus2net.com/javaTerminal Output:
Clean URL 1: www.plus2net.com
Clean URL 2: plus2net.com/java
While trim() strips both ends, replaceFirst("^\\s+", "") strips leading indentation only:
String messy = " Indented source code block";
// Remove leading whitespace only (equivalent to left trim or stripLeading)
String leftTrimmed = messy.replaceFirst("^\\s+", "");
System.out.println("Original: [" + messy + "]");
System.out.println("Left-trimmed:[" + leftTrimmed + "]");Terminal Output:
Original: [ Indented source code block]
Left-trimmed:[Indented source code block]
Calling str.replaceFirst(".", "-") or str.replaceFirst("|", "-") produces unintended modifications. Special characters must be escaped with double backslashes: \\. or \\|.
Like all String class methods, replaceFirst() never mutates the original string. The return value must be assigned back to a variable: str = str.replaceFirst(...).
You can compile and run this complete verification class locally in any Java IDE or environment:
public class StringReplaceFirstFullDemo {
public static void main(String[] args) {
String test = "alpha-beta-alpha-gamma";
// 1. Verify single occurrence replacement
String replaced = test.replaceFirst("alpha", "omega");
if (replaced.equals("omega-beta-alpha-gamma")) {
System.out.println("Check 1 Passed: Only the first match was replaced.");
}
// 2. Verify escaped dot replacement
String file = "report.final.pdf".replaceFirst("\\.", "_");
if (file.equals("report_final.pdf")) {
System.out.println("Check 2 Passed: First literal dot replaced correctly.");
}
// 3. Verify no-op when pattern does not match
String noMatch = test.replaceFirst("zebra", "tiger");
if (noMatch.equals(test)) {
System.out.println("Check 3 Passed: Unmatched pattern returned original string.");
}
System.out.println("All String.replaceFirst() verification checks passed!");
}
}Terminal Output:
Check 1 Passed: Only the first match was replaced.
Check 2 Passed: First literal dot replaced correctly.
Check 3 Passed: Unmatched pattern returned original string.
All String.replaceFirst() verification checks passed!
If no match occurs, replaceFirst() returns the original string instance unchanged.
Yes. Prefix your regular expression with the (?i) flag, e.g. str.replaceFirst("(?i)java", "Python").
No. Passing null as either the regex or the replacement parameter throws a NullPointerException. Guard your variables with isEmpty().
replaceFirst() compiles the regex pattern on every call. In performance-critical loops, compile a static Pattern and use pattern.matcher(str).replaceFirst(repl).
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.