GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Java Matcher.replaceFirst - groups, lambdas, and special characters Java Matcher.replaceFirst MethodLast modified: April 20, 2025
The The method works with a compiled Pattern object and a Matcher that has been applied to an input string. It returns a new string with the first match replaced. The original input string remains unchanged as strings are immutable in Java. Basic Definitions
Pattern: A compiled regular expression that defines the search
pattern. Created using
Matcher: An engine that performs match operations on a character
sequence by interpreting a Pattern. Created using replaceFirst: A Matcher method that replaces the first occurrence of the pattern in the input string with the replacement string. Basic replaceFirst Example
This example demonstrates the simplest use of ReplaceFirstBasic.java
package com.zetcode;
import java.util.regex.*;
public class ReplaceFirstBasic {
public static void main(String[] args) {
String input = "The cat sat on the cat mat.";
String regex = "cat";
String replacement = "dog";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
String result = matcher.replaceFirst(replacement);
System.out.println("Original: " + input);
System.out.println("Modified: " + result);
}
}
The code compiles the regex pattern, creates a matcher for the input string,
then calls Using Regex Metacharacters
This example shows how ReplaceFirstMetacharacters.java
package com.zetcode;
import java.util.regex.*;
public class ReplaceFirstMetacharacters {
public static void main(String[] args) {
String input = "Order 12345 shipped, invoice 67890 pending.";
String regex = "\\d+";
String replacement = "NUMBER";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
String result = matcher.replaceFirst(replacement);
System.out.println("Original: " + input);
System.out.println("Modified: " + result);
}
}
The regex Using Groups in ReplacementThis example demonstrates how to reference captured groups in the replacement string. We reformat the first date found in the input string. ReplaceFirstGroups.java
package com.zetcode;
import java.util.regex.*;
public class ReplaceFirstGroups {
public static void main(String[] args) {
String input = "Dates: 12/25/2023, 01/01/2024, 02/14/2024";
String regex = "(\\d{2})/(\\d{2})/(\\d{4})";
String replacement = "$3-$1-$2"; // YYYY-MM-DD format
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
String result = matcher.replaceFirst(replacement);
System.out.println("Original: " + input);
System.out.println("Modified: " + result);
}
}
The regex captures three groups: month, day, and year. The replacement string
Case Insensitive ReplacementThis example shows how to perform case-insensitive replacement of the first match. We replace the first occurrence of "java" regardless of case. ReplaceFirstCaseInsensitive.java
package com.zetcode;
import java.util.regex.*;
public class ReplaceFirstCaseInsensitive {
public static void main(String[] args) {
String input = "Learn Java, love JAVA, master java.";
String regex = "java";
String replacement = "JAVA";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
String result = matcher.replaceFirst(replacement);
System.out.println("Original: " + input);
System.out.println("Modified: " + result);
}
}
The Using Lambda in ReplacementJava 9 introduced the ability to use a function (lambda) to determine the replacement string. This example doubles the first number found in the string. ReplaceFirstLambda.java
package com.zetcode;
import java.util.regex.*;
public class ReplaceFirstLambda {
public static void main(String[] args) {
String input = "Prices: 10, 20, 30, 40";
String regex = "\\d+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
String result = matcher.replaceFirst(match -> {
int num = Integer.parseInt(match.group());
return String.valueOf(num * 2);
});
System.out.println("Original: " + input);
System.out.println("Modified: " + result);
}
}
The lambda receives the MatchResult and can perform complex logic to generate the replacement. Here we convert the matched number to an integer, double it, and convert back to string. Only the first number (10) is doubled to 20. Replacing Special CharactersThis example shows how to replace the first occurrence of special regex characters by properly escaping them. We replace the first dot with "[dot]". ReplaceFirstSpecialChars.java
package com.zetcode;
import java.util.regex.*;
public class ReplaceFirstSpecialChars {
public static void main(String[] args) {
String input = "example.com www.example.org";
String regex = "\\."; // Escaped dot
String replacement = "[dot]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
String result = matcher.replaceFirst(replacement);
System.out.println("Original: " + input);
System.out.println("Modified: " + result);
}
}
The dot is escaped with Complex Pattern ReplacementThis example demonstrates replacing the first match of a complex pattern. We replace the first HTML tag found in the string with "[TAG]". ReplaceFirstComplex.java
package com.zetcode;
import java.util.regex.*;
public class ReplaceFirstComplex {
public static void main(String[] args) {
String input = "<p>First paragraph</p> <div>Section</div>";
String regex = "<[^>]+>"; // Matches any HTML tag
String replacement = "[TAG]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
String result = matcher.replaceFirst(replacement);
System.out.println("Original: " + input);
System.out.println("Modified: " + result);
}
}
The regex ) is replaced with "[TAG]", while the tag remains unchanged.
SourceJava Matcher.replaceFirst Documentation
We've explored various uses of AuthorMy name is Jan Bodnar, and I am a dedicated programmer with many years of experience in the field. I began writing programming articles in 2007 and have since authored over 1,400 articles and eight e-books. With more than eight years of teaching experience, I am committed to sharing my knowledge and helping others master programming concepts. List all Java tutorials. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |