简体   繁体   English

MAC地址的正则表达式

[英]regex for MAC address

I have the following that I'm using to check for a valid MAC address我有以下用于检查有效 MAC 地址的内容

function isMacValid(mac) {
    var regexMac = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/i
    return regexMac.test(mac);
}

This works for MAC addresses that match the standard of 6 hex values separated by either a hyphen or colon... 1a:2b:3c:4d:5e:6f or e7-f8-90-0a-1b这适用于与 6 个十六进制值标准匹配的 MAC 地址,由连字符或冒号分隔... 1a:2b:3c:4d:5e:6fe7-f8-90-0a-1b

I now need to account for another non-standard notation of just 6 sets of hex with no separators... so 1a2b3c4d5e6f would be acceptable.我现在需要考虑另一种非标准符号,即只有 6 组没有分隔符的十六进制......所以1a2b3c4d5e6f是可以接受的。 How do I now make the : or - optional?我现在如何使 : 或 - 可选?

You can use [:-]?你可以使用[:-]? instead of [:-] .而不是[:-]

The only problem is that 1a:2b:3c:4d:5e6f and 1a-2b:3c:4d:5e:6f will pass the check.唯一的问题是 1a:2b:3c:4d:5e6f 和 1a-2b:3c:4d:5e:6f 将通过检查。 So to avoid that I suggest you to change :所以为了避免这种情况,我建议你改变:

var regexMac = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/i

with

var regexMac = /^((([0-9A-F]{2}:){5})|(([0-9A-F]{2}-){5})|([0-9A-F]{10}))([0-9A-F]{2})$/i

It's less beautifull but works它不那么漂亮但有效

var regexMac = /^([0-9a-fA-F]{2}\W){6}$/i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM