Created
March 20, 2018 10:20
-
-
Save jonurry/1e9a4b78a8fe5859431e48d6587094ef to your computer and use it in GitHub Desktop.
9.3 Numbers Again (Eloquent JavaScript Solutions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // regular expression: | |
| // at the beginning of the number, optionally have '+' or '-' | |
| // followed by a decimal or integer number: | |
| // one or more digits optionally followed by a decimal point followed by zero or more digits, or | |
| // a decimal point followed by one or more digits | |
| // followed by (optionally) at the end of the number: | |
| // 'e' followed by | |
| // '+' or '-' (optional), followed by | |
| // one or more digits | |
| // everything is case-insensitive (i) so 'e' or 'E' are both acceptable | |
| let number = /^[-+]?(\d+\.?\d*|\.\d+)(e[-+]?\d+)?$/i; | |
| // Tests: | |
| for (let str of ["1", "-1", "+15", "1.55", ".5", "5.", | |
| "1.3e2", "1E-4", "1e+12"]) { | |
| if (!number.test(str)) { | |
| console.log(`Failed to match '${str}'`); | |
| } | |
| } | |
| for (let str of ["1a", "+-1", "1.2.3", "1+1", "1e4.5", | |
| ".5.", "1f5", "."]) { | |
| if (number.test(str)) { | |
| console.log(`Incorrectly accepted '${str}'`); | |
| } | |
| } |
Author
Author
Hints
First, do not forget the backslash in front of the period.
Matching the optional sign in front of the number, as well as in front of the exponent, can be done with [+\-]? or (\+|-|) (plus, minus, or nothing).
The more complicated part of the exercise is the problem of matching both "5." and ".5" without also matching ".". For this, a good solution is to use the | operator to separate the two cases — either one or more digits optionally followed by a dot and zero or more digits or a dot followed by one or more digits.
Finally, to make the e case-insensitive, either add an i option to the regular expression or use [eE].
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
9.3 Numbers Again
Write an expression that matches only JavaScript-style numbers. It must support an optional minus or plus sign in front of the number, the decimal dot, and exponent notation —
5e-3or1E10— again with an optional sign in front of the exponent. Also, note that it is not necessary for there to be digits in front of or after the dot, but the number cannot be a dot alone. That is,.5and5.are valid JavaScript numbers, but a lone dot isn’t.