RRegexBuilder
Get RegexBuilder

RegexBuilder · regex answers

Regex for a decimal number

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

An optional minus sign, at least one digit, and an optional fractional part that must itself have digits. It deliberately rejects the trailing-dot form 42. and the bare .5, both of which slip through looser patterns and then break parsing downstream.

What each part does

-?an optional leading minus
\d+the integer part, at least one digit
(\.\d+)?an optional dot followed by at least one digit

Tested against real input

Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.

InputResultMatched
0matches0
-3matches-3
3.14matches3.14
-0.5matches-0.5
3.no match
.5no match
1,5no match
1e3no match
--3no match

The mistake to avoid

Forgetting the locale. In much of Europe the decimal separator is a comma, so 1,5 arrives from a real user and this pattern rejects it.

Try it on your own text

Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.

Open RegexBuilder

Other regex answers