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

Matcher replaceAll() method with example in Java

Thefrom java.util.regex.MatcherThe class represents an engine that performs various matching operations. This class has no constructor, and can be usedmatches()The method of the class java.util.regex.Pattern creates/Get an object of this class.

inreplaceAll()The methods of this (matcher) class accept a string value, replace all matched subsequences with the given string value input, and return the result.

Example1

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 = "[#%&*]";
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Create a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      //Retrieval pattern used
      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);
   }
}

Output Result

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

Example2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
   public static void main(String args[]) {
      //Read a string from the user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Regular expression to match spaces (one or more)
      String regex = "\\s"+";
      //Compile the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieve the matcher object
      Matcher matcher = pattern.matcher(input);
      //Replace all space characters with a single space
      String result = matcher.replaceAll("\s");
      System.out.print("Text after removing unwanted spaces:\n");+result);
   }
}

Output Result

Enter a String
hello this is a sample text with irregular spaces
Text after removing unwanted spaces:
hello this is a sample text with irregular spaces