首先是需要检验1-n位十六进制的正则表达式,用于颜色、mac地址校验
const reghex = /^[A-Fa-f0-9]{1,4}$/;
console.log(reghex.test("A")); // true
console.log(reghex.test("123")); // true
console.log(reghex.test("ABCD")); // true
console.log(reghex.test("abcd")); // true
console.log(reghex.test("12345"));// false
console.log(reghex.test("G123")); // false
console.log(reghex.test("")); // false
如图,1-4位校验,超过则false
^
:确保匹配从字符串的开头开始。[A-Fa-f0-9]
:A-F
匹配大写字母 A 到 F。a-f
匹配小写字母 a 到 f。0-9
匹配数字 0 到 9。
{1,4}
:前面的字符集必须出现1到4次。也就是说,字符串的长度必须在1到4个字符之间。$
:确保匹配到字符串的结尾
二、检验不限长度的十六进制正则表达式
const reghex = /^[A-Fa-f0-9]+$/;
console.log(reghex.test("A")); // true
console.log(reghex.test("123")); // true
console.log(reghex.test("ABCD")); // true
console.log(reghex.test("abcd")); // true
console.log(reghex.test("12345"));// true
console.log(reghex.test("G123")); // false
console.log(reghex.test("")); // false
^
:确保匹配从字符串的开头开始。[A-Fa-f0-9]
:匹配一个十六进制字符。+
:前面的字符集必须出现一次或多次。$
:确保匹配到字符串的结尾。