Regex patterns/Numbers

Decimal number

A number with an optional fractional part — note what the ? applies to.

/^-?\d+(?:\.\d+)?$/
Open it in Rex

The problem

Check that a string is a number that may or may not have a decimal part.

How it reads

start-skip\drepeatgroup\.\drepeatskipend

Follow the line from left to right — every path you can trace is a string this pattern matches.

  1. ^-?\d+(?:\.\d+)?$In order:
  2. ^The start of the text (or of a line with the m flag)
  3. -?The character "-", optionally (zero or one time)
  4. \d+A digit, one or more times, as many as possible
  5. (?:\.\d+)?Repeated optionally (zero or one time):
  6. (?:\.\d+)Group (not captured):
  7. \.\d+In order:
  8. \.The character "."
  9. \d+A digit, one or more times, as many as possible
  10. $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.

More numbers patterns