Regex for Matching Multiple Consecutive Spaces

Matches two or more consecutive space characters, useful for collapsing them into one.

Published October 12, 2026

This regex finds two or more spaces in a row, useful for collapsing them into a single space.

How the pattern works

Breaking the pattern down: {2,} = two or more spaces.

Test your regex against both matching and non-matching inputs; use the Regex tool on this site to experiment live.

Pattern tests

/ {2,}/
✓ 'a b'
✓ 'x y'
✗ 'a b'

Practical examples

The pattern

const re = / {2,}/

Test it

const re = / {2,}/
re.test('a  b')   // true
re.test('x   y')   // true
re.test('a b')   // false

In Python

import re
re.search(r' {2,}', text)

Common mistakes

  • Using \s+ and collapsing newlines.
  • Forgetting the g flag.
  • Collapsing intentionally aligned text.

Key takeaways

  • Anchors (^ and $) make the whole string match instead of a part of it.
  • Regex checks format only; verify data separately when it matters.
  • Test with valid and invalid samples.

FAQ

Collapse all whitespace?

replace(/\s+/g, ' ').

Where can I test this pattern?

Use the Regex Tester on this site, or regex101.com.

More General articles