Java | Removing whitespaces using Regex

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

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 constructed by replacing each matching subsequence by the replacement string, substituting captured subsequences as needed.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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  Everyone  .  Welcome  "
                   "to Geeks for Geeks.";
        System.out.println(removeWhite(s));
    }
}

chevron_right


Output:

HelloEveryone.WelcometoGeeksforGeeks.


My Personal Notes arrow_drop_up

Lets get started

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.