How to check if a line is blank using regex

I am trying to make simple regex that will check if a line is blank or not.

Case;

"    some"   // not blank
"   " //blank
"" // blank

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:

  • regular-expressions.info/Anchors, Character Classes, and Repetition.

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() is 0.
  • boolean String.matches(String regex)
    • Tells whether or not this (entire) string matches the given regular expression.

Actually in multiline mode a more correct answer is this:

/((\r\n|\n|\r)$)|(^(\r\n|\n|\r))|^\s*$/gm

The accepted answer: ^\s*$ does not match a scenario when the last line is blank (in multiline mode).


Try this:

^\s*$

The most portable regex would be ^[ \t\n]*$ to match an empty string (note that you would need to replace \t and \n with tab and newline accordingly) and [^ \n\t] to match a non-whitespace string.