Regex for Splitting a Comma-Separated String
Matches a comma optionally followed by whitespace, used to split CSV-like text into fields.
Published October 13, 2026
This regex splits on commas with optional surrounding whitespace, handy for simple CSV-like lists.
How the pattern works
Breaking the pattern down: \s* = optional spaces; , = comma.
Test your regex against both matching and non-matching inputs; use the Regex tool on this site to experiment live.
Pattern tests
/\s*,\s*/
✓ 'a, b ,c'
✓ '1,2'
✗ 'abc'
Practical examples
The pattern
const re = /\s*,\s*/Test it
const re = /\s*,\s*/
re.test('a, b ,c') // true
re.test('1,2') // true
re.test('abc') // falseIn Python
import re
re.search(r'\s*,\s*', text)Common mistakes
- Quoted fields containing commas.
- Empty items from trailing commas.
- Using regex for real CSV parsing.
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
Parse real CSV?
Use a CSV parser such as PapaParse.
Where can I test this pattern?
Use the Regex Tester on this site, or regex101.com.