Open In App

Java – Remove White Spaces from String using Regex

Last Updated : 26 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Regex is an expression that is used for searching a required pattern or matching a required pattern or Manipulating the input based on requirements by using regex. This Regex is available in java.util.regex.* package in Java Programming. In this article, we will learn to remove the white spaces using Regex.

Prerequisites

Remove White Spaces Using Regex

Here \\s is the shorthand character class which is used to represent any white space characters in the string. And It can include spaces, tabs, line breaks also. The + is the Qualifier which indicates more than one white space. Finally, the Required Regular Expression is \\s+.

Below is the implementation of the above-mentioned regex:

Java




// Java Program to remove
// white spaces using regex
import java.util.regex.*;
  
// Main Class
public class RegexWhiteSpaceExampleOne
{
      // Main method
    public static void main(String[] args) {
          // Input String
        String inputString = "        Welcome to GeeksForGeeks          ";
  
        // Remove white spaces using regex
        String outputString = inputString.replaceAll("\\s+", "");
  
        // Display the results
        System.out.println("Input String:  \"" + inputString + "\"");
        System.out.println("Output String: \"" + outputString + "\"");
    }
}


Output:

ws1

Explaination of the above Program:

In the above code First I take one String value which is already explained in the above after that I use replaceAll String method. To this replaceAll method we pass the regex ‘\s+’. I already explain this regular expression in above you can read it once again if you don’t understand this regex pattern. After that print the inputString value and outputString value.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads