El método replaceAll(String) 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 patrón coincidente en la string del comparador.
Sintaxis:
public String replaceAll(String stringToBeReplaced)
Parámetros: este método toma un parámetro stringToBeReplaced que es la string que se reemplazará en el comparador.
Valor de retorno: este método devuelve una string con la string de destino construida reemplazando la string.
Los siguientes ejemplos ilustran el método Matcher.replaceAll():
Ejemplo 1:
// Java code to illustrate replaceAll() 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 // using replaceAll() method System.out.println("After Replacement: " + matcher .replaceAll(stringToBeReplaced)); } }
Before Replacement: GeeksForGeeks Geeks for For Geeks Geek After Replacement: GFGForGFG GFG for For GFG Geek
Ejemplo 2:
// Java code to illustrate replaceAll() 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 = "GFGFGFGFGFGFGFGFGFG FGF GFG GFG FGF"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Get the String to be replaced String stringToBeReplaced = "GFG"; StringBuilder builder = new StringBuilder(); // Replace every matched pattern // with the target String // using replaceAll() method System.out.println("After Replacement: " + matcher .replaceAll(stringToBeReplaced)); } }
After Replacement: GGFGGGFGGGFGGGFGGFG GFG GFG GFG GFG
Referencia: https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#replaceAll-java.lang.String-
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