English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
thefrom java.util.regex.MatcherThis class represents an engine, performing various matching operations. This class has no constructor, and can be usedmatches()
The method create of the class java.util.regex.Pattern/Get an object of this class.
inreplaceAll()
This (matcher) class method accepts a string value, replaces all matched subsequences with the given string value input, and returns the result.
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++; } //Pattern used for search 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); } }
Résultat de la sortie
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
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReplaceAllExample { public static void main(String args[]) { //Lire une chaîne de l'utilisateur System.out.println("Saisissez une chaîne"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //Expression régulière pour correspondre aux espaces (un ou plusieurs) String regex = "\\s+"; //Compiler l'expression régulière Pattern pattern = Pattern.compile(regex); //Récupérer l'objet du matcheur Matcher matcher = pattern.matcher(input); //Remplacer toutes les espaces par un espace unique String result = matcher.replaceAll(" "); System.out.print("Texte après suppression des espaces indésirables: \n"+result); } }
Résultat de la sortie
Saisissez une chaîne hello this is a sample text with irregular spaces Texte après suppression des espaces indésirables: hello this is a sample text with irregular spaces