English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Meta character"\\s"Matches a space+Represents a space appearing 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[]) { //Read a string from the user System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); 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(" "); System.out.print("Text after removing unwanted spaces: "+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
import java.util.Scanner; public class Test { 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 String regex = "\\s"+"; //Replace pattern with a single space String result = input.replaceAll(regex, " "); System.out.print("Text after removing unwanted spaces: "+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