Skip to content
Regex for Numbers (Integer & Decimal) — Pattern Explained with Examples

Regex for Numbers (Integer & Decimal) — Pattern Explained with Examples

DodaTech Updated Jun 20, 2026 2 min read

Numeric validation is required for form inputs, configuration values, and data parsing. This page covers patterns for integers and decimal numbers with optional sign, decimal places, and scientific notation.

The Pattern

# Integer
/^-?\d+$/

# Decimal
/^-?\d+(\.\d+)?$/

Pattern Breakdown

PartMeaning
^Start-of-string anchor
-?Optional negative sign
\d+One or more digits (0–9)
(\.\d+)?Optional decimal point followed by one or more digits
$End-of-string anchor

Matches

  • (int) 123, -42, 0, 9999, 007
  • (dec) 3.14, -0.5, 100.00, .5, 0.0

Does NOT Match

  • (int) 12.5, --5, abc, 12 34, 1,234
  • (dec) 3.14.15, ., - 1, $100

Language Examples

JavaScript

const intRegex = /^-?\d+$/;
const decRegex = /^-?\d+(\.\d+)?$/;
console.log(intRegex.test('42'));   // true
console.log(decRegex.test('3.14')); // true
console.log(intRegex.test('12.5')); // false

Python

import re
int_pattern = r'^-?\d+$'
dec_pattern = r'^-?\d+(\.\d+)?$'
print(bool(re.match(int_pattern, '42')))    # True
print(bool(re.match(dec_pattern, '3.14')))  # True
print(bool(re.match(int_pattern, '12.5')))  # False

Common Pitfalls

  • Leading zeros (e.g., 007) are valid strings but may be interpreted as octal in some languages — decide whether to accept or reject them based on your use case
  • Commas as thousands separators (e.g., 1,234) are not matched — use ^\d{1,3}(,\d{3})*$ if you need comma support
  • Locale differences: Europe uses 1.000,50 while the US uses 1,000.50 — choose the pattern that matches your locale
  • Trailing decimal point (e.g., 5.) is rejected — require explicit decimal digits with \.\d+
  • The sign must be immediately before the digits with no space — the pattern -?\d+ does not allow whitespace between - and \d

Real-World Use Cases

  • Price validation — ensure user-entered prices are valid decimal numbers before processing payments
  • Configuration parsers — validate numeric configuration values in YAML, JSON, or INI files
  • Data export filtering — filter numeric columns in CSV exports to ensure only valid numbers are processed

FAQ

How do I support scientific notation (e.g., 1.5e10)?
Use ^-?\d+(\.\d+)?[eE][+-]?\d+$. This adds the exponent part: e or E, an optional sign, and one or more digits. Combine with the decimal pattern using alternation for full numeric coverage.
Why does this pattern reject commas in numbers?
Commas are not digits and are not included in \d. A comma-aware pattern for US-style numbers would be ^-?\d{1,3}(,\d{3})*(\.\d+)?$. For European-style (dot as thousands separator, comma as decimal), use a locale-specific pattern instead.

Related Patterns

Regex for CVV Regex for UK Postcode

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro