Regex Match Empty Space: Choosing the Right Whitespace Pattern

How to match spaces, whitespace, blank lines and empty strings with regex, what \s covers in different engines, and when a plain-text approach is safer.

"Empty space" can mean several things in a regular expression: a single space character, any whitespace, a run of spaces, a blank line, an empty string, or invisible characters that look like nothing at all. Each needs a different pattern, and the most common shortcut, \s, behaves differently depending on the regex engine. This review explains what each option matches, what a whitespace-based transformation changes in the text, and when the result stays usable after you copy or share it.

Is a whitespace regex suitable for your task?

A whitespace pattern is a good fit when you need to find, validate, split on or normalize spacing in text you control, such as trimming form input, collapsing repeated spaces in prose, or finding blank lines in a log file. The main benefit is precision: one pattern can handle tabs, line breaks and repeated spaces consistently, which is hard to do by hand.

The decisive tradeoff is that "whitespace" is not one fixed set of characters. The same pattern can match non-breaking spaces in one engine and miss them in another, and a broad pattern like \s also matches line breaks, which can merge lines you meant to keep separate. Replacing or removing whitespace changes the stored text itself, not just how it looks.

A plain-text approach, or no transformation at all, is preferable when whitespace carries meaning: source code indentation, YAML or Python files, Markdown where trailing spaces can create line breaks, fixed-width tables, poetry, or any text where you cannot review the output before it is used. In those cases, a targeted edit or a language-aware formatter is safer than a blanket regex replacement.

Which kind of empty space do you mean?

Goal | Typical pattern | What it matches
A literal space only | " " (a space) or \x20 | The ordinary space character, nothing else
Spaces and tabs on one line | [ \t] or \h (where supported) | Horizontal whitespace, without line breaks
Any whitespace | \s | Spaces, tabs, line breaks and, in some engines, Unicode spaces
One or more whitespace characters | \s+ | A run of whitespace of length at least one
Leading or trailing whitespace | ^\s+|\s+$ | Whitespace at the start or end of the string (or line, with multiline mode)
An empty line | ^$ with multiline mode | A line with no characters at all
A blank line (empty or only whitespace) | ^[ \t]*$ with multiline mode | Lines that look empty, including ones containing spaces or tabs
An entirely empty string | ^$ without multiline mode, or \A\z where supported | Input with zero characters

The distinction between an empty line and a blank line matters in practice: a line containing a single space is invisible on screen but will not match ^$. If you want both, use ^[ \t]$ rather than ^\s$, because \s can also consume the line break and cause the match to span more than one line.

What \s actually covers in different engines

The \s shorthand is the main source of surprises. The behavior below reflects the documented defaults of common engines; options and flags can change it, so check the documentation for the exact version you use.

Engine | Default meaning of \s | Notes
JavaScript | Unicode whitespace and line terminators | Includes the non-breaking space (U+00A0) and the byte order mark (U+FEFF)
Python 3 (str patterns) | Unicode whitespace | The re.ASCII flag restricts it to space, tab, newline, carriage return, form feed and vertical tab
.NET | Unicode whitespace | RegexOptions.ECMAScript changes the behavior to an ASCII-style set
Java | ASCII whitespace only | The UNICODE_CHARACTER_CLASS flag extends it to Unicode whitespace
PCRE (PHP, many tools) | ASCII whitespace | Unicode properties apply when UTF and UCP modes are enabled (the u modifier in PHP enables UTF mode)
Go (RE2) | Tab, newline, form feed, carriage return and space | Does not include the vertical tab or Unicode spaces

The practical consequence: a pattern tested in a browser-based regex tester using JavaScript may match a non-breaking space that the same pattern will miss once it runs in Java or Go. When a tester lets you choose the engine or flavor, set it to match the environment where the pattern will actually run.

Invisible characters that \s does not match

Some characters take up no visible space and are not classified as whitespace by the Unicode White_Space property, so \s will not match them even in Unicode-aware engines. The most common are the zero-width space (U+200B), zero-width non-joiner (U+200C), zero-width joiner (U+200D) and word joiner (U+2060). The byte order mark (U+FEFF) is matched by \s in JavaScript but not in most other engines.

To find these, name them explicitly. Be cautious about removing the zero-width joiner and non-joiner: they are used in some writing systems and in multi-code-point emoji sequences, and deleting them can change how text renders or split one emoji into several.

# Zero-width characters (escape syntax varies by engine)
[\u200B\u200C\u200D\u2060\uFEFF]

# Safer if you only want to remove zero-width spaces and BOMs
[\u200B\uFEFF]

What a whitespace replacement changes

A regex find-and-replace changes the stored characters. This is different from visual adjustments such as CSS letter-spacing or white-space rules, which alter how text is displayed without changing the underlying characters. If you collapse multiple spaces with a regex, anyone who copies, searches or processes the text afterward gets the collapsed version.

# Collapse runs of spaces and tabs into a single space, keeping line breaks
Find:    [ \t]+
Replace: " " (a single space)

# Trim leading and trailing whitespace on every line (multiline mode)
Find:    ^[ \t]+|[ \t]+$
Replace: (empty)

# Remove blank lines (multiline mode)
Find:    ^[ \t]*\r?\n
Replace: (empty)

Two common pitfalls follow from how these patterns work. First, \s* can match zero characters, so a replace-all using \s* may insert the replacement between every character; use \s+ when you mean "at least one." Second, files with Windows line endings contain a carriage return before each newline, so a pattern like [ \t]+$ may not match trailing spaces unless the engine treats \r as part of the line ending or you account for it explicitly.

Will the result stay readable and usable after copying or sharing?

For most prose, normalizing spaces improves consistency without changing meaning. Problems arise in a few predictable areas:

  • Copying patterns: a regex copied from a web page or document may contain a non-breaking space or a typographic character instead of a plain space, so the pattern silently fails to match. Retyping the space or using \x20 avoids this.
  • Code and structured formats: removing or collapsing whitespace can break indentation-sensitive languages, YAML, Makefiles (which require tabs) and fixed-width data.
  • Markdown: two trailing spaces can signal a line break, so trimming trailing whitespace can merge lines in the rendered output.
  • Non-breaking spaces: replacing U+00A0 with a regular space can let text wrap between a number and its unit, or between words that were deliberately kept together.
  • Search and matching: normalized whitespace generally makes text easier to search, but if other systems store the original form, exact-match comparisons between the two versions may fail.

Reading order is not changed by whitespace replacement, since characters stay in the same sequence. Collapsing spaces between words to nothing, however, removes word boundaries, which harms readability for everyone and is likely to affect how assistive technology segments words. No documentation or scoped test of specific screen readers was supplied for this review, so how a particular screen reader handles zero-width characters or unusual Unicode spaces is not confirmed here; test with the assistive technology your audience uses if this matters.

Gaps in this review

No tool-specific tests, version details or measurements were available, so engine behavior above is based on general documented defaults rather than verified observations of a particular regex tester. Engines change across versions, and some tools apply their own preprocessing to input. Before relying on a pattern in production, run it against sample text that includes tabs, non-breaking spaces, Windows line endings and zero-width characters in the same engine and flag configuration you will deploy.