Regex patterns/Numbers
Decimal number
A number with an optional fractional part — note what the ? applies to.
/^-?\d+(?:\.\d+)?$/The problem
Check that a string is a number that may or may not have a decimal part.
How it reads
Follow the line from left to right — every path you can trace is a string this pattern matches.
^-?\d+(?:\.\d+)?$In order:^The start of the text (or of a line with the m flag)-?The character "-", optionally (zero or one time)\d+A digit, one or more times, as many as possible(?:\.\d+)?Repeated optionally (zero or one time):(?:\.\d+)Group (not captured):\.\d+In order:\.The character "."\d+A digit, one or more times, as many as possible$The end of the text (or of a line with the m flag)
Matches
- 3.14
- -0.5
- 42
Does not match
- 1.
- .5
- 1.2.3
- NaN
Where it bites
- The ? applies to the whole group, not just the last character — that is what makes ".14" optional as a unit.
- An unescaped dot means "any character", so ^-?\d+(.\d+)?$ would accept "1x4". Escaping it is not optional.
- Trailing "1." and leading ".5" are rejected here even though JavaScript accepts both as numbers.