In this Java tutorial, you will learn how to replace the first occurrence of a substring in a string using the String.replaceFirst() method. The examples also explain regex behavior, literal substring replacement, special replacement characters, and what happens when the search text is not found.
Replace the first occurrence of a substring in Java using replaceFirst()
To replace only the first occurrence of a string old_string in str1 with new_string, you can use str1.replaceFirst(old_string, new_string). The method returns a new string because Java strings are immutable.
In string processing, you may need to replace only the first match and leave later matches unchanged. For example, you may want to update the first word in a line, replace the first label in a formatted message, or clean only the first matching token in a text value.
The important detail is that replaceFirst() treats its first argument as a regular expression. If you want to replace a plain literal substring that may contain characters such as ., *, ?, [, or (, use Pattern.quote() for the search text.
The syntax of String.replaceFirst() method is given below.
public String replaceFirst(String regex, String replacement)
Here, regex is the pattern to be found, and replacement is the text that replaces the first matched part of the string. For the official method details, see the Java String API documentation.
Java replaceFirst() quick example for first substring replacement
The following short example replaces only the first "Good" in the source string. The second "Good" remains unchanged.
public class Example {
public static void main(String[] args) {
String text = "Good morning. Good evening.";
String result = text.replaceFirst("Good", "Hello");
System.out.println(result);
}
}
Output
Hello morning. Good evening.
Example 1: Replace first occurrence of a substring with another string
In this example, we shall take three strings: str1, old_string and new_string. We shall replace the first occurrence of the string old_string with new_string in str1.
Example.java
public class Example {
public static void main(String[] args) {
String str1 = "Hi! Good morning. Have a Good day.";
String old_string = "Good";
String new_string = "Very-Good";
//replace first occurrence
String resultStr = str1.replaceFirst(old_string, new_string);
System.out.println(resultStr);
}
}
Run the above Java program in console or your favorite IDE, and you shall see an output similar to the following.
Output
Hi! Very-Good morning. Have a Good day.
Only the first occurrence is replaced. Other occurrences are unaffected.
Example 2: replaceFirst() when the search substring is not present
In this example, we shall take three strings: str1, old_string and new_string. We shall try to replace the first occurrence of the string old_string with new_string in str1. But old_string is not present in str1.
Example.java
public class Example {
public static void main(String[] args) {
String str1 = "Hi! Good morning. Have a Good day.";
String old_string = "Bad";
String new_string = "Very-Good";
//replace first occurrence
String resultStr = str1.replaceFirst(old_string, new_string);
System.out.println(resultStr);
}
}
Run the above program.
Output
Hi! Very-Good morning. Have a Good day.
The output block above is from the older version of this example. With old_string = "Bad", the substring is not present in str1, so replaceFirst() returns the original string unchanged.
Correct output for the program above
Hi! Good morning. Have a Good day.
Use Pattern.quote() to replace the first literal substring in Java
Because replaceFirst() uses regex for the search argument, some characters have special meaning. For example, a dot . in regex means “any character”. If you want to replace the first literal dot, quote the search string with Pattern.quote().
Example.java
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
String text = "version 1.2.3";
String oldString = ".";
String newString = "-";
String result = text.replaceFirst(Pattern.quote(oldString), newString);
System.out.println(result);
}
}
Output
version 1-2.3
This replaces only the first literal period. Without Pattern.quote(oldString), the dot would be treated as a regex pattern that can match any single character.
Use Matcher.quoteReplacement() when the replacement contains $ or backslash
The replacement argument also has special handling for characters such as $ and backslash. If the replacement text is user input or may contain these characters, use Matcher.quoteReplacement() to treat it as a literal replacement string.
Example.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
String text = "Price: AMOUNT. Discount: AMOUNT.";
String oldString = "AMOUNT";
String newString = "$10";
String result = text.replaceFirst(
Pattern.quote(oldString),
Matcher.quoteReplacement(newString)
);
System.out.println(result);
}
}
Output
Price: $10. Discount: AMOUNT.
replaceFirst() vs replace() vs replaceAll() in Java strings
Java provides multiple string replacement methods. Choose the method based on whether you want a literal replacement, a regex replacement, the first match only, or all matches.
| Method | Search argument | How many matches are replaced? | Typical use |
|---|---|---|---|
replaceFirst(regex, replacement) | Regex | First match only | Replace the first pattern match |
replace(target, replacement) | Literal character or character sequence | All matches | Replace all plain text matches |
replaceAll(regex, replacement) | Regex | All matches | Replace every pattern match |
If your task is to replace only the first literal substring, replaceFirst(Pattern.quote(oldString), Matcher.quoteReplacement(newString)) is usually the safer form.
Case-insensitive first substring replacement with replaceFirst()
To replace the first occurrence without considering letter case, add the case-insensitive regex flag (?i). When the search text is a literal substring, quote it with Pattern.quote().
Example.java
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
String text = "good morning. Good evening.";
String oldString = "GOOD";
String newString = "Hello";
String regex = "(?i)" + Pattern.quote(oldString);
String result = text.replaceFirst(regex, newString);
System.out.println(result);
}
}
Output
Hello morning. Good evening.
FAQs on replacing only the first substring occurrence in Java
How do I replace the first occurrence of a substring in a Java string?
Use str.replaceFirst(regex, replacement). If the search value is plain text, use Pattern.quote(searchText) so that special regex characters are treated literally.
Does Java replaceFirst() replace all matching substrings?
No. replaceFirst() replaces only the first match. To replace all literal occurrences, use replace(). To replace all regex matches, use replaceAll().
Why does replaceFirst() treat dot, star, and brackets differently?
The first parameter of replaceFirst() is a regular expression. Characters such as ., *, ?, and brackets have regex meanings. Use Pattern.quote() when you want to search for those characters as plain text.
What happens if the substring is not found in replaceFirst()?
If the regex does not match any part of the string, replaceFirst() returns the original string unchanged.
How do I replace the first occurrence ignoring case in Java?
You can use a case-insensitive regex, such as "(?i)" + Pattern.quote(searchText), and pass it to replaceFirst(). This replaces the first match regardless of uppercase or lowercase letters.
QA checklist for Java replaceFirst() tutorial examples
- Confirm that the article explains
replaceFirst()uses regex, not plain literal matching, for the search argument. - Check that examples show only the first occurrence being replaced while later matches remain unchanged.
- Verify that the no-match case returns the original string unchanged.
- Use
Pattern.quote()when the searched substring must be treated as literal text. - Use
Matcher.quoteReplacement()when the replacement can contain$or backslash characters.
Summary: replacing first occurrence of a substring in Java
In this Java Tutorial, we have learned how to replace the first occurrence of a substring with another string. Use replaceFirst() when you need the first regex match replaced. For literal substring replacement, combine it with Pattern.quote(), and quote the replacement with Matcher.quoteReplacement() when special replacement characters may be present.
TutorialKart.com