JS正则表达式检测字符串是否为十六进制数

首先是需要检验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]:匹配一个十六进制字符。
  • +:前面的字符集必须出现一次或多次。
  • $:确保匹配到字符串的结尾。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值