Regex for a Space Character: Literal Spaces, \s and Invisible Unicode
How to match a space character with regex, what \s covers in different engines, and how to find no-break, zero-width and other invisible characters safely.
Short answer
To match one ordinary space, the pattern is a single space character. Writing it as [ ] or \x20 does the same thing and is harder to lose when a pattern is reformatted or trimmed. To match any whitespace, most engines provide \s, but what \s covers depends on the engine and its flags. To find characters that look like spaces, or that take up no room at all, you need explicit Unicode ranges or properties, because several invisible characters are not classed as whitespace and \s will not find them.
Is a whitespace regex the right tool for your task?
For finding and inspecting spacing problems, a Unicode-aware whitespace pattern is usually the right choice. For automatically rewriting text, it needs more care.
- Main benefit: a broad pattern catches look-alike spaces that a literal space misses, such as no-break spaces copied from word processors and web pages.
- Decisive tradeoff: the same breadth also catches characters that carry meaning, including line breaks, no-break spaces that keep a number with its unit, and joiners that hold emoji sequences or some scripts together. Matching is harmless. Replacing is where damage happens.
- When a plain literal space is preferable: use it when the input is known to be plain ASCII and you only care about U+0020. It is clearer and behaves the same in every engine.
- When the original text is preferable: if the text is only displayed and the special spacing is intentional, leaving the original characters untouched is often better than normalizing them.
What each pattern matches
| Pattern | What it matches | Notes |
| (literal space) | U+0020 only | Identical in every engine |
| [ ] or \x20 | U+0020 only | A visible way to write the same pattern |
| \s | ASCII whitespace or Unicode whitespace, depending on engine and flags | See the engine notes below |
| [[:space:]] | POSIX whitespace class | Used in POSIX tools; exact coverage can depend on locale and implementation |
| [[:blank:]] | Space and tab | POSIX; horizontal characters only |
| \h | Horizontal whitespace, including Unicode spaces | Available in PCRE, Perl and Java; not in JavaScript or Python's re module |
| \p{Zs} | Unicode space separators (U+0020, U+00A0, U+1680, U+2000–U+200A, U+202F, U+205F, U+3000) | Requires Unicode property support; excludes tab and line breaks |
| [\u200B-\u200D\u2060] | Zero-width space, zero-width non-joiner, zero-width joiner, word joiner | These are format characters, not whitespace, so \s does not match them |
How \s differs between engines
- JavaScript: \s is always Unicode-aware. It includes the no-break space, the other Unicode space separators, U+2028 and U+2029, and U+FEFF. The u flag is not needed for \s, but it is required (or the v flag) for \p{...} property escapes.
- Python's re module: with str patterns, \s matches Unicode whitespace by default. The re.ASCII flag restricts it to [ \t\n\r\f\v]. The built-in re module does not support \p{...}, but the third-party regex module does.
- Java: by default \s matches only [ \t\n\x0B\f\r]. The UNICODE_CHARACTER_CLASS flag, or (?U) inside the pattern, widens it. \h already includes Unicode horizontal spaces.
- PCRE and engines built on it: \s is ASCII-oriented by default. Unicode behavior requires the UCP option, which can be set with (*UCP) at the start of the pattern where the host allows it.
- .NET: \s is Unicode-aware by default. RegexOptions.ECMAScript restricts it to ASCII behavior.
These are documented defaults, and defaults can change between versions. Check the documentation for the exact engine and version you run, particularly in command-line tools, databases and editors, which often wrap one of these engines with their own options.
Stored characters versus what you see
A regex operates on stored code points, not on appearance. A thin space, an em space and a no-break space can look like a font or layout choice, but each is a distinct character, and each needs to be matched as one. The reverse also holds. Gaps created by CSS letter-spacing, word-spacing, padding or margins contain no character at all, so no regex can find them in the text.
Rendering can also hide what is stored. In HTML, runs of ordinary spaces collapse to a single visible space unless the white-space property preserves them, so two stored spaces may display as one. No-break spaces are not collapsed. Zero-width characters display nothing. Bidirectional controls also stay hidden: these are U+200E, U+200F, U+202A–U+202E and U+2066–U+2069. They can change the order in which mixed left-to-right and right-to-left text appears. They are format characters, not whitespace, so \s does not match them either. The reliable approach is to report code points instead of judging gaps by eye.
const text = "Total:\u00A0120\u202Fkm\u200B";
// \s in JavaScript is Unicode-aware even without the u flag
const whitespace = /\s/g;
// Space separators only; property escapes need the u (or v) flag
const spaceSeparators = /\p{Zs}/gu;
// Zero-width and joiner characters that \s does not match
const zeroWidth = /[\u200B-\u200D\u2060]/g;
// Report code points instead of trusting what the gap looks like
for (const m of text.matchAll(/[\s\u200B-\u200D\u2060]/gu)) {
const cp = m[0].codePointAt(0).toString(16).toUpperCase().padStart(4, "0");
console.log(m.index, "U+" + cp);
}
import re
import unicodedata
text = "Total:\u00a0120\u202fkm\u200b"
# re.ASCII limits \s to [ \t\n\r\f\v]; without it, str patterns are Unicode-aware
ascii_ws = re.compile(r"\s", re.ASCII)
unicode_ws = re.compile(r"\s")
for m in re.finditer(r"[\s\u200b-\u200d\u2060]", text):
ch = m.group()
print(m.start(), f"U+{ord(ch):04X}", unicodedata.name(ch, "<unnamed>"))
Matching versus replacing
Finding characters changes nothing. A replacement changes the stored text, and each of the following choices has a side effect worth deciding on deliberately.
- Replacing \s+ with a single space also collapses line breaks, which flattens paragraphs, lists and line-based data. To keep line breaks, use [^\S\r\n]+ in JavaScript or Python, or \h+ where the engine supports it. In JavaScript, that class still matches U+2028 and U+2029, because \s includes them.
- Converting no-break and narrow no-break spaces to ordinary spaces lets lines break where the author prevented it, such as between a number and its unit, inside some number-grouping styles, or before punctuation in French typography.
- Deleting U+200D (zero-width joiner) splits emoji sequences such as family or profession emoji into their separate component emoji.
- Deleting U+200C (zero-width non-joiner) can change how letters connect in scripts such as Persian, where it prevents joining and affects the written form of words.
- U+FEFF at the very start of a file is usually a byte order mark and is often safe to remove. In the middle of text it acts as a no-break word joiner, so check the context before deleting it.
- Removing bidirectional controls can reorder how mixed-direction text displays. Unexpected controls in source code or identifiers are a known risk because they can make the displayed text differ from its logical order. Flag them for review rather than stripping them silently.
// Collapse runs of horizontal whitespace to one ordinary space, keeping \r and \n
const collapsed = text.replace(/[^\S\r\n]+/g, " ");
// Report, rather than delete, zero-width and bidirectional control characters
const flagged = [...text.matchAll(/[\u200B-\u200D\u2060\u200E\u200F\u202A-\u202E\u2066-\u2069]/g)];
Will the result stay readable and usable after copying or sharing?
Look-alike and invisible spaces are real characters, so they usually travel with copied text. Whether a particular destination keeps, converts or strips them depends on that destination. No destination-specific tests were supplied for this review, so a successful result in one editor, form or messaging app should not be assumed to carry over to others. Test the actual places your text will go.
- Search: a query typed with an ordinary space may not match stored text that contains a no-break space, and a zero-width character inside a word can stop that word from matching, unless the search system normalizes both sides. Normalizing a copy for indexing while keeping the original is a common way to handle this.
- Editing: invisible characters can make cursor movement, selection and deletion behave unexpectedly, because the editor still counts characters the reader cannot see.
- Accessibility: no scoped tests with screen readers or other assistive technology were supplied. How these tools announce no-break spaces, zero-width characters or bidirectional controls can vary by product, version and settings, so test with the tools your audience actually uses. Where a special character serves no purpose, ordinary spaces are the safer default.
- When a plain-text equivalent is needed: normalize to ordinary spaces, and remove stray zero-width characters, in usernames, identifiers, passwords, code, CSV fields, search keys and anything compared by exact match. Keep the original characters in display text where the spacing or joining is intentional.
Gaps in this review
The engine behavior described here reflects documented defaults, not tests of specific versions. Engines, flags and Unicode versions change over time. No measurements were supplied for particular applications, platforms or assistive technologies. Verify behavior against the engine documentation and in the environments where the text will be used before relying on an automated replacement.