Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Removing whitespaces using Regex in Java

  • Difficulty Level : Basic
  • Last Updated : 29 Oct, 2021

Given a string, your task is to remove the whitespaces in the string using Java Regex (Regular Expressions).

Examples

Input :    Hello   Everyone . 
Output : HelloEveryone.

Input :   Geeks  for  Geeks    .
Output : GeeksforGeeks.

Regular Expressions 

Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package. 

Approaches

There are numerous approaches to remove the whitespaces in the string using Regex in Java. A few of them are listed below.

  • Using Regex.Matcher.replaceAll() method
  • Using appendReplacement() method

1. Using Matcher.replaceAll() method

The java.util.regex.Matcher.replaceAll(String replacement) method replaces every subsequence of the input sequence that matches the pattern with the given replacement string.

Declaration: 

public String replaceAll(String replacement) 

Parameters: replacement – The replacement string. 

Return Value: The string is constructed by replacing each matching subsequence with the replacement string, substituting captured subsequences as needed.

The following program demonstrates how to remove the white spaces using a matcher.replaceAll(String replacement) method of util.regex.Pattern class.

Java




// Java program to remove whitespaces from a string
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
public class GeeksforGeeks {
  
    public static String removeWhite(String s) {
      
        // Creating a pattern for whitespaces
        Pattern patt = Pattern.compile("[\\s]");
  
        // Searching patt in s.
        Matcher mat = patt.matcher(s);
  
        // Replacing
        return mat.replaceAll("");
   }
  
    public static void main(String[] argv)
    {
        String s = "   Hello  Geeks  .  ";
        System.out.println(removeWhite(s));
    }
}
Output
HelloGeeks.

2. Using appendReplacement() method

The appendReplacement(StringBuilder, String) method of Matcher Class behaves as an append-and-replace method. This method reads the input string and replaces it with the matched pattern in the matcher string.

Syntax:

public Matcher appendReplacement(StringBuilder builder, String stringToBeReplaced)

Parameters: This method takes two parameters:

  • builder: which is the StringBuilder that stores the target string.
  • stringToBeReplaced: which is the String to be replaced in the matcher.

Return Value: This method returns a Matcher with the target String replaced.

Exception: This method throws the following exceptions:

  • IllegalStateException: If no match has yet been attempted, or if the previous match operation failed.
  • IllegalArgumentException: If the replacement string refers to a named-capturing group that does not exist in the pattern.
  • IndexOutOfBoundsException: If the replacement string refers to a capturing group that does not exist in the pattern.

The following program demonstrates how to remove the white spaces using a matcher.appendReplacement(StringBuilder builder, String stringToBeReplaced) method of util.regex.Pattern class.

Java




// Java program to remove the whiltespaces
// in a string using Java Regex
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
class GFG {
    public static void main (String[] args) {
        
          String input = "   Geeks    for   Geeks  ";
          
          String regex = "\\s";
          String constants = "";
        
          // 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(sb.toString()+constants);
    }
}
Output
GeeksforGeeks            


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!