Regex for Extracting Only Digits From a String
Matches every non-digit character, typically used with a replace to strip everything but digits.
Published October 13, 2026
This regex matches every non-digit so you can remove them and keep only digits.
How the pattern works
Breaking the pattern down: \D = any character that is not a digit.
Test your regex against both matching and non-matching inputs; use the Regex tool on this site to experiment live.
Pattern tests
/\D/
✓ 'abc123'
✓ '(555) 123'
✗ '12345'
Practical examples
The pattern
const re = /\D/Test it
const re = /\D/
re.test('abc123') // true
re.test('(555) 123') // true
re.test('12345') // falseIn Python
import re
re.search(r'\D', text)Common mistakes
- Forgetting the g flag.
- Losing minus signs and decimals.
- Using it to 'validate' numbers.
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
In JavaScript?
str.replace(/\D/g, '').
Where can I test this pattern?
Use the Regex Tester on this site, or regex101.com.