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

Regex to Replace Multiple Spaces With One

Copy the pattern, paste text below, and watch it highlight every run of extra whitespace. Below the tester: how to use it in a replace to tidy messy text.

/ /

What this pattern matches

This matches any run of two or more whitespace characters — spaces, tabs, and newlines. Replace each match with a single space to normalise messy text.

How it works, part by part

\s — any whitespace character: space, tab, newline, carriage return.

{2,} — two or more of them in a row.

How to use it

Run a global replace of \s{2,} with a single space " ". To also trim the ends, combine it with ^\s+|\s+$ or your language's trim function.

Keep single newlines

Because \s includes newlines, this will collapse blank lines too. If you want to keep line breaks, use [ \t]{2,} instead to target only spaces and tabs.

FAQ

Will it collapse newlines as well?

Yes, because \s includes newlines. Use [ \t]{2,} instead if you want to keep line breaks.

How do I also trim the start and end?

Combine this with a trim, or match ^\s+|\s+$ and replace with nothing.