So as an exercise I wanted to match any JS number. This is the one I could come up with:
JavaScript
x
2
1
/^(-?)(0|([1-9]d*?|0)(.d+)?)$/
2
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:
JavaScript
1
2
1
^-?d+(?:_d+)*(?:.d+(?:_d+)*)?$
2
See a regex demo.
Or allowing only a single leading zero:
JavaScript
1
2
1
^-?(?:0|[1-9]d*)(?:_d+)*(?:.d+(?:_d+)*)?$
2
The pattern matches:
^
Start of string-?
Match an optional-
(?:0|[1-9]d*)
Match either0
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.