Regex for Matching a Whitespace-Only String
Matches a string that contains only whitespace characters (or is empty).
Published October 10, 2026
This regex checks whether a string contains only whitespace characters (spaces, tabs, newlines) or is empty.
How the pattern works
Breaking the pattern down: ^ $ = whole string; \s* = zero or more whitespace characters.
Test your regex against both matching and non-matching inputs; use the Regex tool on this site to experiment live.
Pattern tests
/^\s*$/
✓ ' '
✓ '\t\n'
✓ ''
✗ 'a'
✗ ' a '
Practical examples
The pattern
const re = /^\s*$/Test it
const re = /^\s*$/
re.test(' ') // true
re.test('\t\n') // true
re.test('a') // false
re.test(' a ') // falseIn Python
import re
re.search(r'^\s*$', text)Common mistakes
- Forgetting it also matches the empty string.
- Using it instead of str.trim() === ''.
- Unicode non-breaking spaces behaviour.
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
Non-empty whitespace only?
Use ^\s+$.
Where can I test this pattern?
Use the Regex Tester on this site, or regex101.com.