Numbers only regex (digits only)

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 Javascript:

var numberRegex = /^\d+$/;
// Validate numbers
numberRegex.test('12122022'); // Returns true
numberRegex.test('Hey12122022x'); // Returns false

// Extract a number from a string
var numberRegexG = /\d$/g;
'Your message was viewed 203 times'.match(numberRegexG); // 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 Javascript:

var numberRegex = /^(?:-(?:[1-9](?:\d{0,2}(?:,\d{3})+|\d*))|(?:0|(?:[1-9](?:\d{0,2}(?:,\d{3})+|\d*))))(?:.\d+|)$/;
// Validate numbers
numberRegex.test('121220.22'); // Returns true
numberRegex.test('Hey12122022x'); // Returns false

// Extract a real number from a string
var numberRegexG = /(?:-(?:[1-9](?:\d{0,2}(?:,\d{3})+|\d*))|(?:0|(?:[1-9](?:\d{0,2}(?:,\d{3})+|\d*))))(?:.\d+|)/g;
'Pi equals to 3.14'.match(numberRegexG); // 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 JavaScript you can also validate number by trying to parse it using a Number constructor and then using isNaN function of a Number class:

var number = Number('22.2x');
Number.isNaN(number); // returns true