First, we need to match range from 0
to 9
. This range is safe enough so you can just:
let range = /^[0-9]$/;
Then match range from 10
to 99
:
let range = /^([0-9]|[1-9][0-9])$/;
Then match range from 100
to 199
:
let range = /^([0-9]|[1-9][0-9]|1[0-9][0-9])$/;
Then match range from 200
to 249
:
let range = /^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9])$/;
Last, match range from 250
to 255
:
let range = /^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|2[0-5][0-5])$/;
You can narrow down the range pattern using alternative syntax. For example, use \d
in place of [0-9]
:
let range = /^(\d|[1-9]\d|1\d{2}|2[0-4]\d|2[0-5]{2})$/;
Test it!
for (let i = -100; i < 300; ++i) {
if (range.test(i + "")) {
console.log('[' + i + ']');
} else {
console.log(i);
}
}
Matching RGB color string using the range pattern (with permissive white-spaces):
let range = '(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|2[0-5]{2})';
let rgb = new RegExp('^rgb\\(\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + range + '\\s*\\)$');
To match RGBA color string, you need to create alpha range. First, match range from 0
to 1
:
let alpha = /^(0|1)$/;
Then match the decimal point prefixed by 0
:
let alpha = /^(0|0\.[0-9]+|1)$/;
Sometimes, leading zero is not required, so:
let alpha = /^(0|0?\.[0-9]+|1)$/;
Narrow down the pattern:
let alpha = /^([01]|0?\.\d+)$/;
To match RGBA color string:
let range = '(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|2[0-5]{2})';
let alpha = '([01]|0?\\.\\d+)';
let rgb = new RegExp('^rgba\\(\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + alpha + '\\s*\\)$');
To match both RGB and RGBA color string:
let range = '(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|2[0-5]{2})';
let alpha = '([01]|0?\\.\\d+)';
let rgb = new RegExp('^(?:rgb\\(\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + range + '\\s*\\)|rgba\\(\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + alpha + '\\s*\\))$');
Top comments (0)