Tools Viewer

How to Match Spaces and Whitespace in Regex

Published on October 30, 2026 by Hasnain

How to Match Spaces and Whitespace in Regex
How to Match Spaces and Whitespace in Regex

How to Match a Space in Regex: Quick Answer

To match a space in regex, type the space character directly in the pattern, or put it in a character class like [ ]. To match any whitespace, including tabs and line breaks, use \s. To match spaces and tabs but not line breaks, use [ \t]. Add + for one or more, or * for zero or more.

A regex space pattern can mean several different things: one literal space, a run of blanks, any whitespace including tabs and line breaks, or a rule that allows spaces inside a longer value. The safest pattern depends on which job you are actually doing. A literal space is narrow, \s is broad, and a character class such as [ \t] sits in between when you want horizontal whitespace but not newlines.

This guide explains the practical choices for regex whitespace, how to make a regex allow spaces, and \s vs a literal space. You can test every example in RegEx Visualizer, a browser-based regex tester from ToolsViewer that matches with JavaScript RegExp and includes Replace mode and presets such as Whitespace runs. Your pattern and sample text stay on your device in the browser.

Regex Whitespace Cheat Sheet

PatternMatchesTabs?Line breaks?
A typed space or [ ]One ordinary space (U+0020)NoNo
[ ]+One or more ordinary spacesNoNo
[ \t]+Spaces and tabs in a rowYesNo
[^\S\r\n]+Any whitespace except line breaksYesNo
\sOne whitespace characterYesYes
\s+One or more whitespace charactersYesYes
\s*Optional whitespace (can match nothing)YesYes
\S+A run of non-whitespace charactersn/an/a

That distinction is the source of many bugs. A form field that accepts first and last names separated by spaces does not automatically need to accept newlines. A log parser that splits on any spacing may need tabs as well as spaces. A cleanup rule that collapses all whitespace may intentionally turn paragraphs into one line, while a rule that collapses only spaces leaves line breaks alone.

What Does \s Match in Regex?

In JavaScript, \s matches a set of characters, not just the space bar:

  • The ordinary space (U+0020)
  • Tab (\t), line feed (\n), carriage return (\r), vertical tab and form feed
  • The non-breaking space (U+00A0)
  • Other Unicode space separators, the line and paragraph separators, and the byte order mark

It does not match the zero-width space (U+200B). Other regex engines differ in the details, so re-test in your target language if the exact set matters.

The non-breaking space deserves special attention. Text copied from web pages, PDFs and word processors often contains U+00A0 instead of a normal space. A pattern with a literal space silently skips it, while \s matches it. If a pattern "works on my sample but not on pasted text," this is a common cause.

How to Match a Literal Space in Regex

The simplest regex for one literal space is a space typed directly into the pattern. It is easy to miss when reading code, so many teams write [ ] to make the intent visible. Both forms match the same ordinary space character.

To match exactly one space between two words:

regex
^[A-Za-z]+ [A-Za-z]+$

This pattern accepts Jane Doe but rejects a value with two spaces between the names, a tab between them, or a line break between them. If your requirement is one or more spaces, use [ ]+. If it is any horizontal spacing, use [ \t]+. If it is any whitespace at all, including line breaks, use \s+.

How to Allow Spaces in a Regex

To allow spaces inside a value, add the space to a character class, or place a whitespace token between stricter pieces. The first approach suits simple inputs. The second gives you control over where spaces may appear.

  • ^[A-Za-z ]+$ allows ASCII letters and spaces anywhere in the value.
  • ^[A-Za-z]+(?: [A-Za-z]+)*$ allows words separated by single spaces, with no leading or trailing space.
  • ^[A-Za-z]+(?:[ \t]+[A-Za-z]+)*$ allows spaces or tabs between words, but not newlines.
  • ^\s*[A-Za-z]+(?:\s+[A-Za-z]+)*\s*$ allows flexible surrounding whitespace when your program trims later.

Avoid using one broad pattern for every text field. A product title may reasonably accept digits, punctuation and repeated spaces. A person's name may need hyphens and apostrophes. A slug or code usually should not allow spaces at all. Start from the data rules, then choose the smallest pattern that matches them.

Match Spaces and Tabs but Not Newlines

A common requirement is horizontal whitespace only: match spaces and tabs, but stop at the end of a line. You have two reliable options:

  • [ \t]+ is the most readable. It covers ordinary spaces and tabs only.
  • [^\S\r\n]+ reads as not a non-whitespace character, and not \r or \n. It matches every whitespace character except line breaks, including the non-breaking space, so it is the more complete choice for messy pasted text.

Use the first when you control the input, and the second when the text comes from copy and paste.

Collapse Extra Spaces With Replace Mode

Cleanup tasks often need a regex that finds repeated spaces or mixed whitespace. In RegEx Visualizer, load the Whitespace runs preset, paste messy text and open Replace mode. Then compare these patterns:

  • [ ]{2,} finds two or more ordinary spaces.
  • [ \t]+ finds horizontal runs.
  • \s+ finds every whitespace run, including line breaks.

For one-line text, a common replacement is a single space. In JavaScript:

javascript
const clean = text.replace(/[ \t]{2,}/g, " ");

Be careful with \s+. Replacing it globally can turn a multi-line address, stack trace or Markdown list into a single line. A safer first pass is usually [ \t]{2,} replaced with one space, followed by a separate rule for blank lines if needed.

Trim Leading and Trailing Whitespace

Trim-style patterns are useful for analysis and replace previews:

  • ^\s+ matches leading whitespace.
  • \s+$ matches trailing whitespace.
  • ^\s+|\s+$ matches either side (use the g flag).

With the m flag, ^ and $ apply to each line, so ^[ \t]+ can find indentation across a pasted file. In JavaScript code, the built-in trim() method is usually simpler than a regex when you only need to strip both ends of a string.

Optional Spaces Around Separators

Optional spaces belong around separators, not usually around the entire value. For example, \s*,\s* suits a comma-separated list where users may type spaces around the commas. The same idea works for colons, equals signs and pipes.

Be careful with \s* inside repeated groups. Because it can match nothing, it can make a pattern appear to match everywhere, or slow it down on long input. If at least one separator is required, use \s+ instead.

JavaScript Matching and Other Languages

RegEx Visualizer matches with JavaScript RegExp, and the whitespace examples on this page use widely familiar syntax. When a rule later moves into another host language, re-test it there. Export snippets are copy-paste helpers for string quoting and API shape, not substitutes for that language's regex engine.

A pattern copied into a JavaScript string, JSON file, shell command or database migration may need another layer of escaping. For example, \s written inside a normal JavaScript string must become "\\s". Confirm match behavior in the visualizer, then adapt the quoting for your target.

Common Mistakes With Regex Spaces

  • Using \s when a literal space was intended. This can accidentally match newlines and tabs.
  • Forgetting the g flag. Without it, only the first whitespace run is matched.
  • Writing \s* where a separator is required. \s* also matches zero characters.
  • Assuming \w includes spaces. It does not. In common usage it covers letters, digits and underscore.
  • Missing the non-breaking space. A literal-space pattern will not match U+00A0.
  • Testing only clean examples. Add tabs, double spaces, leading spaces, trailing spaces and line breaks before you trust a pattern.

Try It Step by Step

  • Open RegEx Visualizer.
  • Load the Whitespace runs preset, or paste \s+ into the pattern field.
  • Add a sample with single spaces, repeated spaces, a tab and at least one line break.
  • Toggle g to see every run, then compare a literal space, [ \t]+ and \s+.
  • Open Replace and preview collapsing spaces before using the rule on production text.

FAQ

How do I match a space in regex?
Type a space directly in the pattern, or use [ ] to make it visible. Use \s if tabs and line breaks should match too. Try it in RegEx Visualizer.
What is the difference between \s and a literal space?
A literal space matches only the ordinary space character (U+0020). \s matches spaces, tabs, line breaks, the non-breaking space and other Unicode whitespace.
How do I match spaces but not newlines?
Use [ \t]+ for spaces and tabs, or [^\S\r\n]+ for all whitespace except line breaks.
How do I remove extra spaces with regex?
Find [ \t]{2,} with the global flag and replace it with a single space. Preview the result in Replace mode first.
Why doesn't my regex match a space copied from a website?
The copied text probably contains a non-breaking space (U+00A0). A literal space won't match it, but \s will.
How do I trim whitespace with regex?
Use ^\s+|\s+$ with the g flag. In JavaScript, trim() is usually simpler for plain strings.

Conclusion

Matching spaces in regex comes down to choosing the right width. Use a literal space when only U+0020 is acceptable, [ \t] when horizontal whitespace is fine but line breaks are not, and \s when any whitespace should match. Anchor patterns with ^ and $ for validation, add + or * deliberately, and test with tabs, repeated spaces and pasted text before you ship.

Test your patterns live in RegEx Visualizer, then move on to matching newlines and line breaks in regex to handle multi-line text.