Java String replaceFirst(): Replacing the First Regex Match

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().

1. Syntax & Method Signature 🔝

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.

2. Basic replaceFirst() Usage Examples 🔝

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.com

Terminal Output:

Welc*me to plus2net.com
Welnete to plus2net.com

3. Comparison: replaceFirst() vs. replaceAll() vs. replace() 🔝

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.

4. The Regex Metacharacter Trap 🔝

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.4

Terminal Output:

Unescaped dot: -2.0.4
Escaped dot:   v2-0.4

5. Practical Recipe: Stripping Leading Zeros 🔝

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+(?!$)", ""));  // 0

Terminal Output:

Normalized 1: 452
Normalized 2: 0

6. Practical Recipe: Removing URL Protocol Headers 🔝

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/java

Terminal Output:

Clean URL 1: www.plus2net.com
Clean URL 2: plus2net.com/java

7. Practical Recipe: Leading Whitespace Trim (Left Trim) 🔝

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]

8. Common Developer Pitfalls & Traps 🔝

Forgetting that First Argument is Regex

Calling str.replaceFirst(".", "-") or str.replaceFirst("|", "-") produces unintended modifications. Special characters must be escaped with double backslashes: \\. or \\|.

Forgetting String Immutability

Like all String class methods, replaceFirst() never mutates the original string. The return value must be assigned back to a variable: str = str.replaceFirst(...).

9. Complete Compilable Java Program 🔝

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!

10. Frequently Asked Questions (FAQ) 🔝

What happens if the regex pattern is not found?

If no match occurs, replaceFirst() returns the original string instance unchanged.

Can replaceFirst() be made case-insensitive?

Yes. Prefix your regular expression with the (?i) flag, e.g. str.replaceFirst("(?i)java", "Python").

Does replaceFirst() accept null arguments?

No. Passing null as either the regex or the replacement parameter throws a NullPointerException. Guard your variables with isEmpty().

Is replaceFirst() efficient inside high-volume loops?

replaceFirst() compiles the regex pattern on every call. In performance-critical loops, compile a static Pattern and use pattern.matcher(str).replaceFirst(repl).

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer