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 w3wiki " ; // 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:
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.
Java – Remove White Spaces from String using Regex
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.