El método appendTail(StringBuilder) de Matcher Class se comporta como un método de agregar y reemplazar. Este método lee la string de entrada y la agrega al StringBuilder dado en la posición final.
Sintaxis:
public StringBuilder appendTail(StringBuilder builder)
Parámetros: este método toma un generador de parámetros que es el StringBuilder que almacena la string de destino.
Valor de retorno: este método devuelve un StringBuilder con la string de destino reemplazada.
Los siguientes ejemplos ilustran el método Matcher.appendTail():
Ejemplo 1:
// Java code to illustrate appendTail() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(Geeks)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GeeksForGeeks Geeks for For Geeks Geek"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); System.out.println("Before Replacement: " + stringToBeMatched); // Get the String to be replaced String stringToBeReplaced = "GFG"; StringBuilder builder = new StringBuilder(); // Replace every matched pattern // with the target String while (matcher.find()) { matcher .appendReplacement(builder, stringToBeReplaced); } // Add the replaced string at the tail // using the appendTail() method matcher.appendTail(builder); // Print the replaced matcher System.out.println("After Replacement: " + builder.toString()); } }
Producción:
Before Replacement: GeeksForGeeks Geeks for For Geeks Geek After Replacement: GFGForGFG GFG for For GFG Geek
Ejemplo 2:
// Java code to illustrate appendTail() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(FGF)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = " FGF GFG GFG FGF"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); System.out.println("Before Replacement: " + stringToBeMatched); // Get the String to be replaced String stringToBeReplaced = "Geeks"; StringBuilder builder = new StringBuilder(); // Replace every matched pattern // with the target String while (matcher.find()) { matcher .appendReplacement(builder, stringToBeReplaced); } // Add the replaced string at the tail // using the appendTail() method matcher.appendTail(builder); // Print the replaced matcher System.out.println("After Replacement: " + builder.toString()); } }
Producción:
Before Replacement: FGF GFG GFG FGF After Replacement: Geeks GFG GFG Geeks
Referencia: https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#appendTail-java.lang.StringBuilder-
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