All I want is a simple mask for valid JavaScript numbers. I expect a bit of complexity in handling exponents, Hex and the Octal formats all in one, but I wasn’t expecting something this cryptic. I like code that you can simply read, whereas this monstrosity requires a full page of explanation.
/^[+-]?(0[0-7]+|0x[\da-f]+|((0|[1-9]\d*|0\d*[89]\d*)(\.\d*)?|\.\d+)(e[+-]?\d+)?)$/i
Blah!
EDIT: Thanks to Andrea its much improved.
Here’s what I think the regex should look like:
^ [+-]? (
// Octal
0[0-7]+ |
// Hex
0x[\da-f]+ |
(
// Basics: 0, 0., 0.ddd, ddd, ddd. ddd.ddd
(0 | [1-9]\d*) (\.\d*)? |
// Special: decimal parsing of Octal format
0\d*[89]\d* |
// Starting with decimal .nnn
\.\d+
)
// Exponent. Not for Octal or Hex
(e[+-]?\d+)?
) $
It would compile down to the same thing but be much more readable.