Matcher replaceFirst(String) Method in Java with Examples
Last Updated :
10 Nov, 2021
The replaceFirst() method of Matcher Class behaves as an append-and-replace method. This method reads the input string and replaces it with the first matched pattern in the matcher string.
Syntax:
public String replaceFirst(String stringToBeReplaced)
Parameters: The string to be replaced that is the String to be replaced in the matcher.
Return Type: A string with the target string constructed by replacing the string.
Example 1:
Java
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
String regex = "(Geeks)" ;
Pattern pattern = Pattern.compile(regex);
String stringToBeMatched
= "GeeksForGeeks Geeks for For Geeks Geek" ;
Matcher matcher
= pattern.matcher(stringToBeMatched);
System.out.println( "Before Replacement: "
+ stringToBeMatched);
String stringToBeReplaced = "GFG" ;
StringBuilder builder = new StringBuilder();
System.out.println(
"After Replacement: "
+ matcher.replaceFirst(stringToBeReplaced));
}
}
|
Output:
Before Replacement: GeeksForGeeks Geeks for For Geeks Geek
After Replacement: GFGForGeeks Geeks for For Geeks Geek
Example 2:
Java
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
String regex = "(FGF)" ;
Pattern pattern = Pattern.compile(regex);
String stringToBeMatched = "FGF FGF FGF FGF" ;
Matcher matcher
= pattern.matcher(stringToBeMatched);
System.out.println( "Before Replacement: "
+ stringToBeMatched);
String stringToBeReplaced = "GFG" ;
StringBuilder builder = new StringBuilder();
System.out.println(
"After Replacement: "
+ matcher.replaceFirst(stringToBeReplaced));
}
}
|
Output:
Before Replacement: FGF FGF FGF FGF
After Replacement: GFG FGF FGF FGF
Share your thoughts in the comments
Please Login to comment...