English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to remove spaces using Java regex (RegEx)

The regular expression "\\s" matches the spaces in the string. ThereplaceAll()method accepts a string and replaces the matched characters with the given string. To remove all whitespace from the input string, bypass the aforementioned regular expression and an empty string as input, and callreplaceAll()method.

Example1

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

Output Result

Result: Hiwelcometow3codebox

Example2

Similarly,appendReplacement()The method accepts a string buffer and a replacement string, and appends the matched characters with the given replacement string 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);
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Match the compiled pattern in the string
      Matcher matcher = pattern.matcher(input);
      //Create 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: 
"+ sb.toString()+constants );
   }
}

Output Result

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

Example3

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

Result: This is a sample text with spaces