Java – Remove White Spaces from String using Regex
Last Updated :
26 Jan, 2024
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
import java.util.regex.*;
public class RegexWhiteSpaceExampleOne
{
public static void main(String[] args) {
String inputString = " Welcome to GeeksForGeeks " ;
String outputString = inputString.replaceAll( "\\s+" , "" );
System.out.println( "Input String: \"" + inputString + "\"" );
System.out.println( "Output String: \"" + outputString + "\"" );
}
}
|
Output:
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.
Share your thoughts in the comments
Please Login to comment...