Java Matcher.replaceFirst Method
Last modified: April 20, 2025
The Matcher.replaceFirst
method is part of Java's regex package. It
replaces the first subsequence of the input sequence that matches the pattern
with the given replacement string. This method is useful when you need to modify
only the first occurrence of a pattern in a string.
The method returns a new string where the first match is replaced. The original string remains unchanged as strings in Java are immutable. The replacement can include references to captured groups from the pattern.
Basic Usage of replaceFirst
The simplest use of replaceFirst
is to replace the first occurrence
of a pattern with a fixed string. The method takes the replacement string as
parameter and returns the modified string. The original matcher's input remains
unchanged.
package com.zetcode; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReplaceFirstBasic { public static void main(String[] args) { String input = "The quick brown fox jumps over the lazy dog"; Pattern pattern = Pattern.compile("fox"); Matcher matcher = pattern.matcher(input); String result = matcher.replaceFirst("cat"); System.out.println("Original: " + input); System.out.println("Modified: " + result); } }
In this example, we replace the first occurrence of "fox" with "cat". The
replaceFirst
method scans the input string and replaces only the
first match it finds. The output shows the original string and the modified
version.
Replacing with Group References
replaceFirst
supports references to captured groups in the
replacement string. Group references are written as $n
where n is
the group number. This allows dynamic replacements based on the matched content.
package com.zetcode; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReplaceFirstGroups { public static void main(String[] args) { String input = "John has 3 apples, Jane has 5 oranges"; Pattern pattern = Pattern.compile("(\\w+) has (\\d+) (\\w+)"); Matcher matcher = pattern.matcher(input); String result = matcher.replaceFirst("$1 gave away $2 $3"); System.out.println("Original: " + input); System.out.println("Modified: " + result); } }
This example captures three groups: name, quantity, and item. The replacement string uses these groups to construct a new sentence. Only the first match is modified, while subsequent matches remain unchanged in the output string.
Case Insensitive Replacement
When you need case-insensitive matching for replacement, you can use the
CASE_INSENSITIVE
flag. This ensures the pattern matches regardless
of case differences. The replacement itself doesn't change the case of the
replacement string.
package com.zetcode; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReplaceFirstCaseInsensitive { public static void main(String[] args) { String input = "The Quick Brown Fox jumps over the lazy dog"; Pattern pattern = Pattern.compile("quick", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(input); String result = matcher.replaceFirst("slow"); System.out.println("Original: " + input); System.out.println("Modified: " + result); } }
Here, "Quick" is matched despite the case difference due to the
CASE_INSENSITIVE
flag. The replacement string "slow" is inserted
with its original casing. Only the first match is replaced, leaving other
occurrences unchanged.
Replacing Special Characters
replaceFirst
can handle patterns containing special regex
characters. When your replacement string contains dollar signs or backslashes,
you need to escape them properly. Java provides methods to help with this.
package com.zetcode; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReplaceFirstSpecialChars { public static void main(String[] args) { String input = "Price: $10.50, Discount: 5%"; Pattern pattern = Pattern.compile("\\$\\d+\\.\\d{2}"); Matcher matcher = pattern.matcher(input); // Replacement contains $ which is special in regex String result = matcher.replaceFirst(Matcher.quoteReplacement("USD 10.50")); System.out.println("Original: " + input); System.out.println("Modified: " + result); } }
This example demonstrates replacing a price pattern containing dollar signs. The
Matcher.quoteReplacement
method escapes special characters in the
replacement string. This prevents them from being interpreted as group
references or other special sequences.
Replacing with Function
Java 9 introduced the replaceFirst
overload that accepts a
Function<MatchResult, String>
. This allows dynamic replacement
based on the match result. The function receives match details and returns the
replacement string.
package com.zetcode; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.function.Function; public class ReplaceFirstFunction { public static void main(String[] args) { String input = "The temperature is 23.5°C and 75.2°F"; Pattern pattern = Pattern.compile("(\\d+\\.\\d+)°([CF])"); Matcher matcher = pattern.matcher(input); Functionconverter = match -> { double value = Double.parseDouble(match.group(1)); String unit = match.group(2); if (unit.equals("F")) { double celsius = (value - 32) * 5/9; return String.format("%.1f°C", celsius); } return match.group(); // no conversion for Celsius }; String result = matcher.replaceFirst(converter); System.out.println("Original: " + input); System.out.println("Modified: " + result); } }
This example converts the first temperature it finds to Celsius if it's in Fahrenheit. The function examines the match result and performs the conversion. Only the first temperature is converted, demonstrating selective replacement.
Replacing in Multiline Text
When working with multiline text, replaceFirst
can target the first
match across multiple lines. The MULTILINE
flag changes how
anchors work, but doesn't affect replacement behavior directly.
package com.zetcode; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReplaceFirstMultiline { public static void main(String[] args) { String input = "First line\nSecond line\nThird line"; Pattern pattern = Pattern.compile("^.*line$", Pattern.MULTILINE); Matcher matcher = pattern.matcher(input); String result = matcher.replaceFirst("Replaced line"); System.out.println("Original:\n" + input); System.out.println("\nModified:\n" + result); } }
This example replaces the first line that ends with "line". The
MULTILINE
flag makes ^
and $
match line
boundaries. The replacement affects only the first matching line in the
multiline input string.
Performance Considerations
When using replaceFirst
repeatedly, it's more efficient to reuse
the Pattern and Matcher objects. Creating new Pattern instances for each
replacement has significant overhead due to regex compilation.
package com.zetcode; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReplaceFirstPerformance { public static void main(String[] args) { String[] inputs = { "Error: File not found", "Error: Permission denied", "Warning: Low disk space" }; // Efficient approach: reuse compiled pattern Pattern pattern = Pattern.compile("Error: "); long startTime = System.nanoTime(); for (String input : inputs) { Matcher matcher = pattern.matcher(input); String result = matcher.replaceFirst("Alert: "); System.out.println(result); } long duration = System.nanoTime() - startTime; System.out.println("\nTime taken (reusing pattern): " + duration + " ns"); } }
This example demonstrates the performance benefit of reusing the Pattern instance. The compiled regex is used for multiple replacements, avoiding recompilation. The timing shows the efficiency of this approach compared to compiling the pattern for each replacement.
Source
Java Matcher.replaceFirst Documentation
In this article, we've explored various aspects of the
Matcher.replaceFirst
method. From basic usage to advanced
techniques, this method provides powerful string manipulation capabilities
for Java developers.
Author
List all Java tutorials.