English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Meta character"\\s"Matches a space+Indicates that a space appears once or multiple times, therefore, the regular expression \\ S +Matches all space characters (single or multiple). Therefore, replace multiple spaces with a single space.
Match the input string with the above regular expression and then replace the result with a single space "".
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReplaceAllExample { public static void main(String args[]) { //Lecture de la chaîne utilisateur System.out.println("Saisissez une chaîne"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "\\s"+"; //Compilation de l'expression régulière Pattern pattern = Pattern.compile(regex); //Récupération de l'objet de correspondance Matcher matcher = pattern.matcher(input); //Remplacer tous les caractères d'espace 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
import java.util.Scanner; public class Test { public static void main(String args[]) { //Lecture de la chaîne 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 String regex = "\\s"+"; //Remplacer le modèle avec un espace unique String result = input.replaceAll(regex, " "); 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