Last active
August 7, 2019 05:22
-
-
Save yuezk/f2ccb980e80732a2edbab13fad1854f6 to your computer and use it in GitHub Desktop.
[ECMAScript] Regexp to match the JavaScript numberic literal value (Supports number seprator)
This file contains 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
// Reference: http://www.ecma-international.org/ecma-262/10.0/index.html#prod-NumericLiteral | |
(function () { | |
const regexp = /^[+-]?(?:0b[01]+|0o[0-7]+|0x[0-9a-f]+|(?:(?:(?:0|[1-9]\d*)\.\d*|\.\d+|(?:0|[1-9]\d*))(?:e[+-]?\d+)?))$/i; | |
// RegExp below also supports number spearator: https://github.com/tc39/proposal-numeric-separator | |
// const regexp = /^[+-]?(?:0b[01](_?[01])*|0o[0-7](_?[0-7])*|0x[0-9a-f](_?[0-9a-f])*|(?:(?:(?:0|[1-9](_?\d(_?\d)*)?)\.(\d(_?\d)*)?|\.\d(_?\d)*|(?:0|[1-9](_?\d(_?\d)*)?))(?:e[+-]?\d(_?\d)*)?))$/i; | |
const testCases = [ | |
'0.', '0.E1', '0.e-1','0.e0', '0.1', '0.12', '0.12e2', '0.12e-2','0.12E0','0.0e1', '0.0e-1', '0.0E0', | |
'1.', '1.E1', '1.e-1','1.e0', '1.1', '1.12', '1.12e2', '1.12e-2','1.12E0','1.0e1', '1.0e-1', '1.0E0', | |
'1_0.', '1_0_0.', '1_0.0_1_2', '1_0_0', '100_000', '1e1_2', '1e+12_0', '.1_2_3', '.000_111', '10_1.1_2_3', '0.000_111', '0e0', '1_2e10', | |
'11.', '12.E1', '13.e-1','144.e0', '155.1', '124.12', '14.12e2', '124.12e-2','10.12E0','100.0e1', '101.0e-1', '102.0E0', | |
'.0', '.0e1', '.0e-1', '.0E0', '.12', '.12e1', '.12e-1', '.12E0', | |
'0', '0e1', '0e-1', '0E0', '1', '1e1', '1e-1', '1E0', | |
'0b0', '0b1', '0b0000', '0b111', '0b010101', '0b0_1', '0b0000_1111', | |
'0B0', '0B1', '0B0000', '0B111', '0B010101', | |
'0o0','0o01','0o02','0o07','0o7', '0o00_11', '0o0_1111_00', | |
'0O0','0O01','0O02','0O07','0O7', | |
'0x0', '0x01', '0xa', '0x1234abcdef', '0xf_ed_123', '0x1234_abcd_ef', | |
'0X0', '0X01', '0XA', '0X1234ABCDEF', | |
]; | |
testCases.forEach((num) => { | |
console.assert(regexp.test(num), num); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment