Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to replace multiple spaces in a string using a single space using Java regex?
The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.
Match the input string with the above regular expression and replace the results with single space “ ”.
Example 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\s+";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
//Replacing all space characters with single space
String result = matcher.replaceAll(" ");
System.out.print("Text after removing unwanted spaces: \n"+result);
}
}
Output
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
Example 2
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression to match space(s)
String regex = "\s+";
//Replacing the pattern with single space
String result = input.replaceAll(regex, " ");
System.out.print("Text after removing unwanted spaces: \n"+result);
}
}
Output
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
Advertisements
