Skip to content
Advertisement

Regex match any js number

So as an exercise I wanted to match any JS number. This is the one I could come up with:

/^(-?)(0|([1-9]d*?|0)(.d+)?)$/

This however doesn’t match the new syntax with underscore separators (1_2.3_4). I tried a couple of things but I couldn’t come up with something that would work. How could I express all JS numbers in one regex?

Advertisement

Answer

For the format in the question, you could use:

^-?d+(?:_d+)*(?:.d+(?:_d+)*)?$

See a regex demo.

Or allowing only a single leading zero:

^-?(?:0|[1-9]d*)(?:_d+)*(?:.d+(?:_d+)*)?$

The pattern matches:

  • ^ Start of string
  • -? Match an optional -
  • (?:0|[1-9]d*) Match either 0 or 1-9 and optional digits
  • (?:_d+)* Optionally repeat matching _ and 1+ digits
  • (?: Non capture group
    • .d+(?:_d+)* Match . and 1+ digits and optionally repeat matching _ and 1+ digits
  • )? Close non capture group
  • $ End of string

See another regex demo.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement