Regex Not Empty String: Patterns That Check for Content, and Where They Fall Short

How to match a non-empty or non-blank string with a regular expression, what each common pattern really tests, and when a plain length or trim check is the better choice.

A request for a regex that matches a "not empty string" usually means one of two different requirements. Either the input must contain at least one character of any kind, or it must contain at least one character that is not whitespace. The patterns for these differ, and so do their edge cases. This review covers what each common pattern actually checks, where it is reliable, and when skipping regex is the more practical choice.

Short recommendation

For a strict "not empty" check in code you control, a length comparison is clearer than any regex and has no engine-specific behavior. Use a regex when the rule has to live somewhere that only accepts a pattern, such as a form attribute, a validation schema, a config file, a routing rule or a linter. The main benefit of a pattern is that it is declarative and portable. The main tradeoff is that anchors, newline handling and the meaning of whitespace vary between engines and flags, so a pattern that looks correct can accept input you meant to reject. If you can write ordinary code, a check such as trimming the value and testing its length is usually easier to read and review.

Empty versus blank: decide first

Requirement | Accepts | Rejects
Not empty (length > 0) | "a", " ", a lone newline | "" only
Not blank (has non-whitespace) | "a", " a ", "a" followed by a newline | "", " ", tabs and newlines only

Most form fields that people describe as "required" really need the not-blank rule, because a value made only of spaces is rarely useful. Pick the rule before choosing a pattern; most bugs in this area come from using a not-empty pattern where a not-blank rule was intended.

Common patterns and what they actually match

The pattern most often suggested is ^.+$. It works for single-line input, but in most engines the dot does not match line terminators unless a dotall flag is set. As a result, multi-line input such as text from a textarea fails the check even though it clearly has content. To match any character including newlines, use [\s\S] or enable the dotall flag. Note that ^.+$ also accepts a string of spaces, so it is a not-empty check, not a not-blank check.

Another widely used pattern is ^(?!\s*$).+$. The negative lookahead rejects strings made only of whitespace, and .+ requires at least one character. It is a valid not-blank check for single-line input, but it shares the same newline limitation. The simplest not-blank test is an unanchored search for one non-whitespace character, \S. It does not need anchors, because finding a single such character anywhere is enough.

// JavaScript

// Not empty: at least one character of any kind
/^[\s\S]+$/.test(value)   // equivalent to value.length > 0

// Not blank: at least one non-whitespace character
/\S/.test(value)

// Not blank, written as a whole-string match (dotall flag allows newlines)
/^(?!\s*$).+$/s.test(value)
# Python
import re

# Not blank: search for any non-whitespace character
bool(re.search(r"\S", value))

# Whole-string form; fullmatch avoids the trailing-newline behavior of $
re.fullmatch(r"\s*\S[\s\S]*", value) is not None

In HTML forms, the pattern attribute is matched against the entire value, as if it were anchored. It is not checked at all when the field is empty, so it cannot enforce "not empty" on its own. Use required to reject empty values and a pattern to reject whitespace-only values. Single-line text inputs strip line breaks from their value, so a dot is safe there. The textarea element does not support the pattern attribute, so multi-line fields need validation in script or on the server.

<input name="title" required pattern=".*\S.*">

What the check changes, and what it does not

A regex test reads the stored characters and returns a yes or no; it does not modify the text. This is different from trimming or normalizing, which do change what is stored. If you validate a value as not blank but save it untrimmed, the leading and trailing spaces remain in your data. Decide separately whether to trim before saving.

A regex also works on characters, not on what the text looks like on screen. A string that appears empty can still contain characters that pass a not-blank check. In JavaScript, the zero-width space (U+200B), word joiner (U+2060) and soft hyphen (U+00AD) are not matched by \s, so a value consisting only of a zero-width space passes /\S/ even though it displays as nothing. Python's str patterns also do not treat the zero-width space as whitespace. The non-breaking space (U+00A0) is matched by \s in JavaScript and in Python str patterns, but engines or modes restricted to ASCII, such as Python with the ASCII flag or bytes patterns, treat it as an ordinary non-whitespace character.

Copied, pasted and shared input

Text pasted from documents, chat apps, web pages or spreadsheets often carries non-breaking spaces, zero-width characters, byte order marks or trailing newlines. These invisible characters determine whether a not-blank check passes, so the check that worked on typed test input may behave differently on real pasted input. If a field must contain visible content, consider ignoring format characters during validation. Engines with Unicode property support, including JavaScript with the u flag, PCRE and Java, can match the format-character category with \p{Cf}. Python's built-in re module does not support \p; the third-party regex module does.

// JavaScript: ignore format characters (zero-width space, joiners, BOM) for the check only
const visible = value.replace(/\p{Cf}/gu, "");
const notBlank = /\S/.test(visible);

Strip these characters only for the check, not from the stored value. The format category includes the zero-width joiner, which is part of many emoji sequences and is needed for correct rendering in some scripts. Removing it from saved text can change how the text displays.

On accessibility, the browser's built-in message for a pattern mismatch is generic and does not explain the rule. Give the field a visible label or hint that states the requirement, and show a clear error message linked to the field, rather than relying on the pattern alone. No assistive-technology test results were available for this review, so specific screen reader behavior is not described here.

Engine differences to check before relying on a pattern

  • In Python, Java and PCRE, $ can match just before a final newline. Use \Z in Python, \z in Java and PCRE, or a full-match API when the whole string must match.
  • The dot excludes line terminators unless dotall is enabled: the s flag in JavaScript, re.DOTALL in Python, Pattern.DOTALL in Java.
  • Which Unicode spaces \s covers depends on the engine and its flags.
  • A JavaScript regex with the g or y flag keeps lastIndex between test calls, so reusing one regex object can return alternating results. Do not use those flags for a simple validation test.
  • Java's matches() requires the whole string to match, while find() searches. Python's match() anchors only at the start; fullmatch() anchors at both ends.

Gaps and how to verify

No test results, benchmarks or version-specific observations were supplied for this review. The behavior described above follows the documented semantics of each engine. Before relying on a pattern, run it in your actual engine, with your actual flags, against a small set of edge cases like the one below.

""            expect: fail both checks
" "           expect: not empty, but blank
"\t\n"        expect: not empty, but blank
"\u00A0"      expect: depends on whitespace rules in your engine and mode
"\u200B"      expect: passes \S; decide whether it should
"a"           expect: pass both checks
" a "         expect: pass; decide whether to trim before storing
"a\nb"        expect: pass; fails ^.+$ without dotall
"a\n"         expect: pass; check $ behavior in your engine