replaceFirst: Replacing Only the First Occurrence
You'll learn how to replace just the first match of a pattern in a String, leaving subsequent occurrences untouched.
The Core Idea
While the replace method you've already learned replaces all occurrences of a target substring, sometimes you only want to replace the first one. The replaceFirst(String regex, String replacement) method does exactly that—it scans your string from left to right, finds the first match of the pattern, replaces it, and stops there.
Think of it like a spelling correction tool that fixes only the first typo it encounters in a document, leaving the rest for you to review manually.
How It Works
The method takes two parameters:
regex: A regular expression pattern to search for (though you can use simple literal strings too)replacement: The string to substitute for the first match
String text = "apple apple apple";
String result = text.replaceFirst("apple", "orange");
System.out.println(result); // "orange apple apple"
Only the first "apple" becomes "orange"—the other two remain unchanged.
Using Simple Patterns
Even though it accepts regex patterns, you can use it with plain text:
String log = "Error: timeout. Error: not found.";
String fixed = log.replaceFirst("Error", "Warning");
System.out.println(fixed); // "Warning: timeout. Error: not found."
Why Use replaceFirst?
This method is perfect when you need surgical precision: updating the first occurrence of a header, correcting the opening instance of a repeated term, or modifying just the initial match in a stream of data while preserving the rest.
Key Takeaway: Use replaceFirst(String regex, String replacement) to replace only the first occurrence of a pattern in a String, leaving all subsequent matches unchanged.