English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Метасимволы«\\s»Сопоставление с пробелом, + означает, что пробел может встречаться один или несколько раз, поэтому регулярное выражение \\s+ соответствует всем пробельным символам (одному или нескольким). Таким образом, можно заменить несколько пробелов одним пробелом.
Сопоставьте входную строку с указанным регулярным выражением и замените результат на один пробел «».
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReplaceAllExample { public static void main(String args[]) { //Чтение строки от пользователя System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "\\s+"; //Компилирование регулярного выражения Pattern pattern = Pattern.compile(regex); //Извлечение объекта мatcher Matcher matcher = pattern.matcher(input); //Использование одного пробела для замены всех пробелов String result = matcher.replaceAll(" "); System.out.print("Text after removing unwanted spaces: \n"+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
import java.util.Scanner; public class Test { public static void main(String args[]) { //Чтение строки от пользователя System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //Регулярное выражение для匹配а пробелов String regex = "\\s+"; //Использование одного пробела для замены шаблона String result = input.replaceAll(regex, " "); System.out.print("Text after removing unwanted spaces: \n"+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