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.
Regex pattern
/\s{2,}/g
This matches any run of two or more whitespace characters; replace each match with a single space to collapse repeated spaces, tabs and newlines. Pair it with a trim to also drop leading and trailing whitespace.
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.
Use it in your code
import re
text = "This line has too much space.\tAnd\t\ttabs too."
pattern = r'''\s{2,}'''
for m in re.finditer(pattern, text):
print(m.group())
const text = "This line has too much space.\tAnd\t\ttabs too.";
const re = new RegExp(String.raw`\s{2,}`, "g");
console.log(text.match(re));
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.