Numbers only regex (digits only) Python

Numbers only (digits only)

Numbers only (or digits only) regular expressions can be used to validate if a string contains only numbers.

Basic numbers only regex

Below is a simple regular expression that allows validating if a given string contains only numbers:

"^\\d+$"

Test it!
/^\d+$/

True

False

Enter a text in the input above to see the result

Example code in Python:

import re

# Validate number
number_pattern = "^\\d+$"
re.match(number_pattern, '42') # Returns Match object
re.match(number_pattern, 'notanumber') # Returns None

# Extract number from a string
number_extract_pattern = "\\d+"
re.findall(number_extract_pattern, 'Your message was viewed 203 times.') # returns ['203']

Real number regex

Real number regex can be used to validate or exact real numbers from a string.

"^(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)$"

Test it!
/^(?:-(?:[1-9](?:\d{0,2}(?:,\d{3})+|\d*))|(?:0|(?:[1-9](?:\d{0,2}(?:,\d{3})+|\d*))))(?:.\d+|)$/

True

False

Enter a text in the input above to see the result

Example code in Python:

# Validate real number
number_pattern = "^(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)$"
re.match(number_pattern, '121220.22') # Returns Match object
re.match(number_pattern, 'Hey12122022x') # Returns None

# Extract real number from a string
number_extract_pattern = "(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)"
re.findall(number_extract_pattern, 'Pi equals to 3.14') # returns ['3.14']

Test it!

True

False

Enter a text in the input above to see the result

Notes on number only regex validation

In Python you can also validate number by using isnumeric method:

"123".isnumeric() # returns True
"xx".isnumeric() # returns False