How to remove white spaces using Java Regular Expression (RegEx)


The regular expression “\s” matches the spaces in a string. The replaceAll() method accepts a string and a regular expression replaces the matched characters with the given string. To remove all the white spaces from an input string, invoke the replaceAll() method on it bypassing the above mentioned regular expression and an empty string as inputs.

Example 1

public class RemovingWhiteSpaces {
   public static void main( String args[] ) {
      String input = "Hi welcome to tutorialspoint";
      String regex = "\s";
      String result = input.replaceAll(regex, "");
      System.out.println("Result: "+result);
   }
}

Output

Result: Hiwelcometotutorialspoint

Example 2

Similarly, the appendReplacement() method accepts a string buffer and a replace string and, appends the matched characters with the given replace string and appends to the string buffer.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RemovingWhiteSpaces {
   public static void main( String args[] ) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string: ");
      String input = sc.nextLine();
      String regex = "\s";
      String constants = "";
      System.out.println("Input string: \n"+input);
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      //Creating an empty string buffer
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {
         constants = constants+matcher.group();
         matcher.appendReplacement(sb, "");
      }
      matcher.appendTail(sb);
      System.out.println("Result: \n"+ sb.toString()+constants );
   }
}

Output

Enter input string:
this is a sample text with white spaces
Input string:
this is a sample text with white spaces
Result:
thisisasampletextwithwhitespaces

Example 3

public class Just {
   public static void main(String args[]) {
      String input = "This is a sample text with spaces";
      String str[] = input.split(" ");
      String result = "";
      for(int i=0; i<str.length; i++) {
         result = result+str[i];
      }
      System.out.println("Result: "+result);
   }
}

Output

Result: Thisisasampletextwithspaces

Updated on: 21-Nov-2019

880 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements