Regular expression to check number
How to choose a regular expression that checks numbers: integers, decimals, exponents and US separators, plus anchoring, Unicode digit and pasted-input pitfalls.
What a number-checking regex actually does
A regular expression that checks a number tests whether a string has a particular shape, such as "optional sign, then digits, then an optional decimal part." It returns a match or no match. It does not convert the text to a numeric value, round it, or change the stored characters. That makes it different from text transformation tools that reverse, mirror or restyle characters. Those tools rewrite or re-render text. A validation pattern only reads it. If a regex tester also offers replace or reformat features, treat those as separate operations with their own effects.
Is a regex the right tool for your check?
A regex is a good fit when you need to confirm that input has an exact textual format before it is stored, transmitted or parsed. Its main benefit is precision: you can state exactly which characters and arrangements are allowed. The main tradeoff is that a pattern only knows about characters. It cannot know whether the number is in range, fits a data type, or means what the user intended. When you need the numeric value, your language's number parser followed by explicit range checks is usually clearer and safer than a more elaborate pattern.
- A regex fits well for: enforcing a strict format such as digits only, a fixed number of decimal places, or no leading zeros.
- A regex fits well for: rejecting input before it reaches a parser that would accept unwanted formats, such as hexadecimal, whitespace or exponents.
- Parsing is preferable for: range limits, overflow, floating-point precision and any locale-aware interpretation.
- Parsing is preferable for: cases where a long pattern would be hard for the next maintainer to read and verify.
Decide what "a number" means first
Most broken number patterns come from an unstated definition. Before choosing a pattern, answer these questions. Is a leading plus or minus sign allowed? Are leading zeros such as 007 acceptable? Is a decimal point allowed, and may it appear without digits on one side, as in .5 or 5.? Is scientific notation such as 1e5 valid? Are thousands separators allowed, and in which convention? In the US convention, the comma groups thousands and the period marks decimals. Are surrounding spaces tolerated? And are only ASCII digits 0 through 9 acceptable?
Common patterns
The patterns below use [0-9] for ASCII digits and are anchored with ^ and $. Each one also relies on the anchoring behavior covered in the next section. They use only basic features: character classes, groups, alternation and quantifiers. These features behave the same way in the common engines, including those in JavaScript, Python, Java, .NET, PCRE and Ruby.
Digits only: ^[0-9]+$
Optional sign: ^[+-]?[0-9]+$
No leading zeros: ^[+-]?(0|[1-9][0-9]*)$
Decimal, digits both sides: ^[+-]?[0-9]+(\.[0-9]+)?$
Decimal, also .5 and 5.: ^[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)$
With exponent: ^[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)?$
US thousands separators: ^[+-]?([0-9]{1,3}(,[0-9]{3})*|[0-9]+)(\.[0-9]+)?$
- 007 matches digits only. It is rejected by the no-leading-zeros pattern.
- -0 matches the no-leading-zeros pattern. Reject it separately if a negative zero is meaningless for your data.
- 1e5 matches only the exponent pattern.
- 1,234.5 and 1234 both match the thousands pattern. 12,34 and 1,2345 do not, because each group after a comma must have exactly three digits.
- An empty string matches none of these patterns, because each requires at least one digit.
Anchors and full matches
Without anchors, a search finds digits anywhere in the input, so abc123 would pass a bare [0-9]+. Anchors are not identical across engines. JavaScript's $ without the m flag matches only at the end of the input. Python, Java and PCRE also let $ match just before a final newline, so 42 followed by a newline can pass. In Ruby, ^ and $ always match at line boundaries, so a multi-line input can pass if any one line is a number. Use \A and \z in Ruby, Java, .NET and PCRE. In Python, use re.fullmatch, which requires the whole string to match.
import re
INTEGER = re.compile(r"[+-]?(0|[1-9][0-9]*)")
def is_integer(text: str) -> bool:
return INTEGER.fullmatch(text) is not None
const INTEGER = /^[+-]?(0|[1-9][0-9]*)$/;
function isInteger(value) {
return INTEGER.test(value);
}
In JavaScript, avoid the g or y flag on a reused pattern that you call with test(). With those flags, the regex keeps a lastIndex position between calls, so the same input can alternate between passing and failing.
Why \d is not always the same as [0-9]
The shorthand \d means different things in different engines. In JavaScript it matches only ASCII 0 through 9. In Python 3 string patterns it matches any Unicode decimal digit unless you pass re.ASCII. In .NET it matches Unicode decimal digits unless you use the ECMAScript option. In Java it is ASCII by default unless you enable UNICODE_CHARACTER_CLASS. In a Unicode-aware engine, fullwidth digits, Arabic-Indic digits or the styled bold digits produced by "fancy font" generators can all pass \d. Whatever runs next may handle those characters differently. If you mean ASCII digits, write [0-9].
A regex checks format, not value
A string of twenty nines passes every integer pattern above, yet it does not fit in a 64-bit integer. A decimal with many places passes, yet it may lose precision as a floating-point value. Ranges can be written as patterns. For example, ^(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$ accepts 0 through 255 without leading zeros. Such patterns are harder to read and harder to change than parsing the value and comparing it with the limits. A practical split is to use a simple pattern for shape and the parser for value.
Copied and pasted input
Pasted values often contain characters the user cannot see. Common ones include leading or trailing spaces and non-breaking spaces (U+00A0). The narrow no-break space (U+202F) appears as a thousands separator in some locales. Others include zero-width spaces (U+200B), byte order marks, and directional marks (U+200E, U+200F, U+061C) carried over from right-to-left text. Typeset documents may also use a true minus sign (U+2212) instead of the hyphen-minus. A strict, anchored [0-9] pattern rejects all of these. That is correct for machine-to-machine data, but it can frustrate people pasting from documents.
If you want to accept such input, normalize it explicitly before checking, and store the normalized result. Trimming handles ordinary whitespace. Unicode NFKC normalization maps fullwidth digits and the mathematical styled digits to ASCII digits. It does not convert the minus sign U+2212 to a hyphen-minus, and it does not remove zero-width or directional characters. Those need their own handling. Normalize first and validate second, so the stored value is exactly what the pattern approved.
The pattern itself also needs care when you copy it. A pattern copied from a regex tester into source code may need extra escaping. In a non-raw string literal, . must be written as \. to reach the engine intact. JSON and shell quoting add their own escaping layers. Features beyond the basics, such as lookbehind, possessive quantifiers and named groups, vary by engine and version. Confirm support in the engine where the pattern will run, not just in the tester.
Accessibility and form fields
In HTML forms, the pattern attribute must match the entire value, so you do not need anchors there. A text input with inputmode="numeric" plus a pattern gives you exact format control. The number input type applies its own parsing, and browsers differ in what they let users type into it. Whichever you choose, state the expected format in visible text and repeat it in the error message. A rejection that simply says "invalid" does not tell anyone, including screen reader users, how to fix the entry. No assistive technology testing was supplied for this review. Test error announcements with the screen readers and browsers your audience actually uses, rather than assuming one working setup generalizes.
Validation itself has no effect on search or editing. Normalization does: if you store a canonical form, such as no separators and ASCII digits, searches and comparisons will work on that form. Keep the original input only if you need it for display or auditing.
What could not be verified here
No tool-specific evidence or engine test results were supplied for this review. The pattern behaviors described above follow from how the patterns are constructed and from documented engine behavior. They are not observed results from a particular tester. Before relying on a pattern, run it in the exact engine and version you will deploy. Use inputs that probe each decision you made, such as the set below. The last two lines contain fullwidth digits and a Unicode minus sign.
""
"0"
"-0"
"007"
"1."
".5"
"1e5"
"1,000"
"1,00"
" 42"
"42\n"
"42"
"−5"