在前端开发中,处理表单时,常遇到对 IPv6/Ipv4
地址合法性校验的场景。
斯蒂芬·瑞恩(Stephen Ryan)写了一个非常有用的正则表达式,可用于匹配任何一个合法的IPv6地址。以下为正则表达式的代码
const ipv6Regexp = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
// full form of IPv6
ipv6Regexp.test('fe80:0000:0000:0000:0204:61ff:fe9d:f156');
=> true
// drop leading zeroes
ipv6Regexp.test('fe80:0:0:0:204:61ff:fe9d:f156');
=> true
// collapse multiple zeroes to :: in the IPv6 address
ipv6Regexp.test('fe80::204:61ff:fe9d:f156');
=> true
// IPv4 dotted quad at the end
ipv6Regexp.test('fe80:0000:0000:0000:0204:61ff:254.157.241.86');
=> true
// drop leading zeroes, IPv4 dotted quad at the end
ipv6Regexp.test('fe80:0:0:0:0204:61ff:254.157.241.86');
=> true
// dotted quad at the end, multiple zeroes collapsed
ipv6Regexp.test('fe80::204:61ff:254.157.241.86');
=> true
// localhost
ipv6Regexp.test('::1');
=> true
// link-local prefix
ipv6Regexp.test('fe80::');
=> true
// global unicast prefix
ipv6Regexp.test('2001::');
=> true
以 CIDR
表示法匹配IP地址的正则表达式。
$ npm i -S cidr-regex
const cidrRegex = require('cidr-regex');
// Contains a CIDR IP address?
cidrRegex().test('foo 192.168.0.1/24');
=> true
// Is a CIDR IP address?
cidrRegex({exact: true}).test('foo 192.168.0.1/24');
=> false
cidrRegex.v6({exact: true}).test('1:2:3:4:5:6:7:8/64');
=> true
// Extract CIDRs from string
'foo 192.168.0.1/24 bar 1:2:3:4:5:6:7:8/64 baz'.match(cidrRegex());
=> ['192.168.0.1/24', '1:2:3:4:5:6:7:8/64']
使用正则可视化工具,便捷/快速分析表达式结构
Regulex
是开源的正则可视化工具,实时展示可视化效果,方便正则调试,可视化美观等。点击查看