regexhelper
Test a pattern. Copy a ready-made one. No signup.

Regex to Match Whitespace

Copy the pattern, paste your text, and watch every space, tab and line break light up. Below: what \s matches and how to collapse runs.

Regex pattern

/\s+/g

This matches one or more consecutive whitespace characters — spaces, tabs and line breaks. Use the global flag to find every run; replace with '' to delete or ' ' to normalise.

/ /

What this pattern matches

\s+ matches one or more whitespace characters in a row: regular spaces, tabs (\t), newlines (\n), carriage returns and vertical tabs. The + groups consecutive whitespace into a single match, which is exactly what you want when collapsing messy spacing.

Collapse runs to a single space

Replace every match with one space: text.replace(/\s+/g, ' '). To also trim the ends, add .trim().

Match only horizontal whitespace

If you must keep line breaks, use [ \t]+ instead of \s+ so newlines are left untouched.

Use it in your code

Python
import re
text = "one  two\tthree\nfour     five"
pattern = r'''\s+'''
for m in re.finditer(pattern, text):
    print(m.group())
JavaScript
const text = "one  two\tthree\nfour     five";
const re = new RegExp(String.raw`\s+`, "g");
console.log(text.match(re));

FAQ

Does \s match newlines?

Yes. \s covers spaces, tabs, newlines, carriage returns, form feeds and vertical tabs. Use [ \t] if you want horizontal whitespace only.

How do I collapse multiple spaces into one?

Replace /\s+/g with a single space, then .trim() the result.

Why use + after \s?

Without +, each whitespace character is a separate match. With +, a run of spaces or a tab-plus-space becomes one match, which is what you want for cleanup.