Start free · Free tools · Fair usage limits
Browse Tools

Categories

Custom AI Solutions – AI2Flows
LIVE NEWS
Loading latest AI & SEO news…
Home›Tools›Regex Tester›Regex: Multiple spaces
Regex pattern · find & extract

Regex: Multiple spaces

Regex to replace multiple spaces: a tested pattern with examples, a plain-English breakdown, and code for JavaScript, Python, PHP, Java and Go.

Quick answer

Use / {2,}/g with the global flag to find every match. In "too many spaces here" it finds " ", " ". Use \s{2,} to also collapse tabs and newlines, but that will join lines too.

Last updated · Maintained by FreeAIToolz · How we test

/ {2,}/g

2 match(es)

too many spaces here single spaces only
Open in the full Regex Tester (replace, flags, groups) →

How this regex works

PartMeaning
{2,}two or more consecutive space characters

Flags: g finds every match instead of stopping at the first.

Examples

InputMatches
too many spaces here ,
single spaces onlynone

Every example above is checked automatically in JavaScript and Python each time the site is built.

Limitations and edge cases

Use \s{2,} to also collapse tabs and newlines, but that will join lines too.

When to use this pattern

Collapsing double spaces in content cleanup: replace matches with a single space.

Use it in your language

JavaScript

const matches = text.match(/ {2,}/g) ?? [];

Python

import re
matches = [m.group(0) for m in re.finditer(r' {2,}', text)]

PHP

preg_match_all('~ {2,}~', $text, $m);
$matches = $m[0];

Java

Matcher m = Pattern.compile(" {2,}").matcher(text);
while (m.find()) { System.out.println(m.group()); }

Go

re := regexp.MustCompile(` {2,}`)
matches := re.FindAllString(text, -1)

More regex patterns

Frequently asked questions

What is the regex for multiple spaces?
/ {2,}/g. Use \s{2,} to also collapse tabs and newlines, but that will join lines too.
Which languages does this pattern work in?
It is tested in JavaScript and Python and uses syntax that also works in PHP (PCRE) and Java. It also works in Go’s RE2 engine.
How do I replace the matches?
In JavaScript use text.replace(/ {2,}/g, "replacement"); in Python use re.sub(r' {2,}', "replacement", text).