Regex for Numbers Only: Extracting and Validating Numeric Data
Master regex patterns for working with numbers. Learn to extract, validate, and filter numeric data from strings.
Working with numbers through regular expressions is fundamental in data validation and extraction. This guide covers patterns for different numeric scenarios.
Basic Number Pattern
Match any sequence of digits:
^\d+$
This matches one or more digits from start to end of string.
JavaScript Implementation
function isNumbersOnly(str) {
return /^\d+$/.test(str);
}
console.log(isNumbersOnly('12345')); // true
console.log(isNumbersOnly('123a45')); // false
console.log(isNumbersOnly('12.34')); // false
Decimal Numbers
Allow decimal points:
^\d+(\.\d+)?$
This pattern matches whole numbers or decimals with precision.
Examples
const decimalRegex = /^\d+(\.\d+)?$/;
console.log(decimalRegex.test('123')); // true
console.log(decimalRegex.test('123.45')); // true
console.log(decimalRegex.test('123.')); // false
console.log(decimalRegex.test('.45')); // false
Negative Numbers
Include optional minus sign:
^-?\d+(\.\d+)?$
The -? makes the minus sign optional.
Usage
const numberRegex = /^-?\d+(\.\d+)?$/;
console.log(numberRegex.test('-123')); // true
console.log(numberRegex.test('-123.45')); // true
console.log(numberRegex.test('123')); // true
console.log(numberRegex.test('--123')); // false
Extracting Numbers from Text
Find all numbers in a string:
function extractNumbers(text) {
const matches = text.match(/\d+/g);
return matches ? matches.map(Number) : [];
}
console.log(extractNumbers('I have 5 apples and 10 oranges'));
// Output: [5, 10]
Specific Number Ranges
Phone Numbers
^\d{10}$ // Exactly 10 digits
^\d{3}-\d{3}-\d{4}$ // Format: 123-456-7890
Postal Codes
^\d{5}$ // US: 5 digits
^\d{5}-\d{4}$ // US extended: 12345-6789
Credit Card Numbers
^\d{13,19}$ // 13-19 digits
Currency Amounts
Match monetary values:
^\$?\d+(\.\d{2})?$
Implementation
const currencyRegex = /^\$?\d+(\.\d{2})?$/;
console.log(currencyRegex.test('100')); // true
console.log(currencyRegex.test('$99.99')); // true
console.log(currencyRegex.test('50.5')); // false (needs 2 decimals)
Real-World Examples
Form Validation
function validateAge(age) {
return /^\d{1,3}$/.test(age) && parseInt(age) > 0 && parseInt(age) < 120;
}
console.log(validateAge('25')); // true
console.log(validateAge('150')); // false
console.log(validateAge('abc')); // false
Extract Product IDs
function extractProductIds(text) {
const regex = /ID:\s*(\d+)/g;
const matches = [];
let match;
while ((match = regex.exec(text)) !== null) {
matches.push(match[1]);
}
return matches;
}
const text = 'ID: 123, ID: 456, ID: 789';
console.log(extractProductIds(text)); // ['123', '456', '789']
Parse Version Numbers
function parseVersion(version) {
const regex = /(\d+)\.(\d+)\.(\d+)/;
const match = version.match(regex);
if (!match) return null;
return {
major: parseInt(match[1]),
minor: parseInt(match[2]),
patch: parseInt(match[3])
};
}
console.log(parseVersion('1.2.3')); // { major: 1, minor: 2, patch: 3 }
Common Patterns Reference
| Purpose | Pattern | Example |
|---|---|---|
| Integers only | ^\d+$ | 12345 |
| Decimals | ^\d+(\.\d+)?$ | 123.45 |
| Negatives | ^-?\d+$ | -123 |
| Phone | ^\d{10}$ | 5551234567 |
| Postal code | ^\d{5}$ | 10001 |
| Currency | ^\$?\d+(\.\d{2})?$ | $99.99 |
Performance Considerations
Simple number patterns like ^\d+$ are very efficient. More complex patterns with multiple groups or quantifiers may impact performance with large datasets.
Optimization Tips
// Fast - simple pattern
/^\d+$/.test(input)
// Slower - multiple groups
/^(\d+)\.(\d+)\.(\d+)$/.test(input)
// For repeated tests, compile pattern once
const numberRegex = /^\d+$/;
while (hasMoreData) {
numberRegex.test(nextItem); // Reuse pattern
}
Edge Cases
// Leading zeros
/^\d+$/.test('00123') // true - might not be desired
// Very large numbers
/^\d+$/.test('99999999999999999999') // true - JavaScript handles this fine
// Scientific notation (not matched)
/^\d+$/.test('1e5') // false - use different pattern for scientific
Summary
Number validation with regex ranges from simple patterns for basic digits to complex patterns for specific formats. Choose the simplest pattern that solves your problem, as complex regex is harder to maintain and debug. For complex numeric validation, consider supplementing regex with range checks and type validation in your application logic.
Average reading pace: 200 words per minute
Share Article
Related Articles
Regex for Email Validation: Building Robust Patterns
Learn how to create reliable email validation patterns using regular expressions. Explore different approaches and their trade-offs.
Comprehensive Regex Cheat Sheet: Syntax and Examples
A complete reference guide for regular expressions. Contains all essential patterns, flags, and examples for quick lookup.
Common Regex Examples: Practical Patterns for Daily Development
Explore practical regex patterns you'll use regularly. Learn phone numbers, URLs, postal codes, and more.