English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Método Matcher replaceAll() con ejemplo en Java

java.util.regex.Matcher中的类代表一个引擎,进行各种匹配操作。此类没有构造函数,可以使用matches()类java.util.regex.Pattern的方法创建/获取此类的对象。

replaceAll()此(匹配器)类的方法接受字符串值,替换所有匹配的子序列与 给定的字符串值的输入,并返回结果。

Ejemplo1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[#%&*]";
      //创建一个模式对象
      Pattern pattern = Pattern.compile(regex);
      //创建一个Matcher对象
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //检索使用的模式
      System.out.println("The are "+count+" special characters [# % & *] in the given text");
      //Replacing all special characters [# % & *] with ! String result = matcher.replaceAll("!");
      System.out.println("Replaced all special characters [# % & *] with !: \n"+result);
   }
}

Resultado de salida

Enter input text:
Hello# How # are# you *& welcome to T#utorials%point
The are 7 special characters [# % & *] in the given text
Replaced all special characters [# % & *] with !:
Hello! How ! are! you !! welcome to T!utorials!point

Ejemplo2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
   public static void main(String args[]) {
      //Leer una cadena del usuario
      System.out.println("Ingrese una cadena");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Expresión regular para coincidir con los espacios (uno o más)
      String regex = "\\s+";
      //Compilar la expresión regular
      Pattern pattern = Pattern.compile(regex);
      //Recuperar el objeto del complementador
      Matcher matcher = pattern.matcher(input);
      //Reemplace todos los caracteres de espacio con un solo espacio
      String result = matcher.replaceAll(" ");
      System.out.print("Texto después de eliminar espacios no deseados: \n"+result);
   }
}

Resultado de salida

Ingrese una cadena
hello this is a sample text with irregular spaces
Texto después de eliminar espacios no deseados:
hello this is a sample text with irregular spaces