Home > Software design >  Regex match any js number
Regex match any js number

Time:02-25

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?

CodePudding user response:

how about this?

^(-?)(0|([1-9]*?(\_)?(\d)|0|)(\.\d )?(\_)?(\d))$

CodePudding user response:

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.

  • Related