The pattern you want is something like this in multiline mode:
^\s*$
Explanation:
^
is the beginning of string anchor.$
is the end of string anchor.\s
is the whitespace character class.*
is zero-or-more repetition of.
In multiline mode, ^
and $
also match the beginning and end of the line.
References:
A non-regex alternative:
You can also check if a given string line
is “blank” (i.e. containing only whitespaces) by trim()
-ing it, then checking if the resulting string isEmpty()
.
In Java, this would be something like this:
if (line.trim().isEmpty()) {
// line is "blank"
}
The regex solution can also be simplified without anchors (because of how matches
is defined in Java) as follows:
if (line.matches("\\s*")) {
// line is "blank"
}
API references
String String.trim()
- Returns a copy of the string, with leading and trailing whitespace omitted.
boolean String.isEmpty()
- Returns
true
if, and only if,length()
is0
.
- Returns
boolean String.matches(String regex)
- Tells whether or not this (entire) string matches the given regular expression.