Regex Whitespace in Java

A Regular Expression or regex is a combination of special characters that creates a search pattern that can be used to search for certain characters in Strings. In the following example, we will see how we can use various regex characters to find whitespaces in a string.
Find Whitespace Using Regular Expressions in Java
To use the regex search pattern and see if the given string matches the regex, we use the static method matches()
of the class Pattern
. The method matches()
takes two arguments: the first is the regular expression, and the second is the string we want to match.
The most common regex character to find whitespaces are \s
and \s+
. The difference between these regex characters is that \s
represents a single whitespace character while \s+
represents multiple whitespaces in a string.
In the below program, we use Pattern.matches()
to check for the whitespaces using the regex \s+
and then the string with three whitespaces. Then, we print whitespaceMatcher1
that outputs true
, meaning that the pattern matches and finds whitespaces.
In whitespaceMatcher2
, we use the character \s
to identify single whitespace which returns true for the string " "
. Note that regular expressions are case-sensitive and that \S
is different from \s
.
Next, we use the regex [\\t\\p{Zs}]
which is equivalent to \s
and returns true for a single whitespace.
\u0020
is a Unicode character representing space and returns true when a string with single whitespace is passed.
And the last regex \p{Zs}
is also a whitespace separator that identifies whitespace.
import java.util.regex.Pattern;
public class RegWhiteSpace {
public static void main(String[] args) {
boolean whitespaceMatcher1 = Pattern.matches("\\s+", " ");
boolean whitespaceMatcher2 = Pattern.matches("\\s", " ");
boolean whitespaceMatcher3 = Pattern.matches("[\\t\\p{Zs}]", " ");
boolean whitespaceMatcher4 = Pattern.matches("\\u0020", " ");
boolean whitespaceMatcher5 = Pattern.matches("\\p{Zs}", " ");
System.out.println("\\s+ ----------> " + whitespaceMatcher1);
System.out.println("\\s -----------> " + whitespaceMatcher2);
System.out.println("[\\t\\p{Zs}] --> " + whitespaceMatcher3);
System.out.println("\\u0020 ------->" + whitespaceMatcher4);
System.out.println("\\p{Zs} ------->" + whitespaceMatcher5);
}
}
Output:
\s+ ----------> true
\s -----------> true
[\t\p{Zs}] --> true
\u0020 ------->true
\p{Zs} ------->true
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedInRelated Article - Java Regex
- Use Regex in the String.contains() Method in Java
- Use \s in Java
- String Matches Regex in Java
- Regex Special Characters in Java
Related Article - Java Regex
- Use Regex in the String.contains() Method in Java
- Use \s in Java
- String Matches Regex in Java
- Regex Special Characters in Java