El método appendTail(StringBuffer) 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 StringBuffer dado en la posición final.
Sintaxis:
public StringBuffer appendTail(StringBuffer buffer)
Parámetros: este método toma un búfer de parámetros que es el StringBuffer que almacena la string de destino.
Valor de retorno: este método devuelve un StringBuffer 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 = "GEEKS"; StringBuffer buffer = new StringBuffer(); // Replace every matched pattern // with the target String while (matcher.find()) { matcher.appendReplacement(buffer, stringToBeReplaced); } // Add the replaced string at the tail // using the appendTail() method matcher.appendTail(buffer); // Print the replaced matcher System.out.println("After Replacement: " + buffer.toString()); } }
Before Replacement: GeeksForGeeks Geeks for For Geeks Geek After Replacement: GEEKSForGEEKS GEEKS for For GEEKS 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 FGF FGF 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 = "GFG"; StringBuffer buffer = new StringBuffer(); // Replace every matched pattern // with the target String while (matcher.find()) { matcher.appendReplacement(buffer, stringToBeReplaced); } // Add the replaced string at the tail // using the appendTail() method matcher.appendTail(buffer); // Print the replaced matcher System.out.println("After Replacement: " + buffer.toString()); } }
Before Replacement: FGF FGF FGF FGF After Replacement: GFG GFG GFG GFG
Referencia: https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#appendTail-java.lang.StringBuffer-
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