El método replaceFirst() de Matcher Class se comporta como un método de agregar y reemplazar. Este método lee la string de entrada y la reemplaza con el primer patrón coincidente en la string del comparador.
Sintaxis:
public String replaceFirst(String stringToBeReplaced)
Parámetros: la string que se reemplazará que es la string que se reemplazará en el comparador.
Tipo de retorno: una string con la string de destino construida reemplazando la string.
Ejemplo 1:
Java
// Java Program to Illustrate replaceFirst() Method // of Matcher class // Importing required classes import java.util.regex.*; // Main class public class GFG { // Main driver method public static void main(String[] args) { // Getting the regex to be checked String regex = "(Geeks)"; // Creating a pattern from regex Pattern pattern = Pattern.compile(regex); // Getting the String to be matched String stringToBeMatched = "GeeksForGeeks Geeks for For Geeks Geek"; // Creating a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Displaying the string to be matched // before replacing System.out.println("Before Replacement: " + stringToBeMatched); // Getting the string to be replaced String stringToBeReplaced = "GFG"; StringBuilder builder = new StringBuilder(); // Replacing every matched pattern with the target // string using replaceFirst() method System.out.println( "After Replacement: " + matcher.replaceFirst(stringToBeReplaced)); } }
Producción:
Before Replacement: GeeksForGeeks Geeks for For Geeks Geek After Replacement: GFGForGeeks Geeks for For Geeks Geek
Ejemplo 2:
Java
// Java Program to Illustrate replaceFirst() Method // Importing required classes import java.util.regex.*; // Main class public class GFG { // Main driver method public static void main(String[] args) { // Getting the regex to be checked String regex = "(FGF)"; // Creating a pattern from regex Pattern pattern = Pattern.compile(regex); // Getting the string to be matched String stringToBeMatched = "FGF FGF FGF FGF"; // Creating a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Printing string on console // before replacement System.out.println("Before Replacement: " + stringToBeMatched); // Getting the string to be replaced String stringToBeReplaced = "GFG"; StringBuilder builder = new StringBuilder(); // Replacing every matched pattern with target // string using replaceFirst() method and printing // the string to be replaced System.out.println( "After Replacement: " + matcher.replaceFirst(stringToBeReplaced)); } }
Producción:
Before Replacement: FGF FGF FGF FGF After Replacement: GFG FGF FGF FGF
Publicación traducida automáticamente
Artículo escrito por Kirti_Mangal y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA