[javascript]代码库
匹配IP地址
先说说网上流传的版本:
\d+\.\d+\.\d+\.\d+
\d 数字没有限制
修正如下:
var rip = /^(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])$/;
rip.test( "192.168.1.1" ) // true
rip.test( "0.0.0.0" ) // true
rip.test( "255.255.255.255" ) // true
rip.test( "256.255.255.255" ) // false
进一步增加分组:
var rip2 = /^([01]?\d{1,2}|2[0-4]\d|25[0-5])\.([01]?\d{1,2}|2[0-4]\d|25[0-5])\.([01]?\d{1,2}|2[0-4]\d|25[0-5])\.([01]?\d{1,2}|2[0-4]\d|25[0-5])$/;
rip2.exec( "192.168.1.1" ) // ["192.168.1.1", "192", "168", "1", "1"]
rip2.exec( "0.0.0.0" ) // ["0.0.0.0", "0", "0", "0", "0"]
rip2.exec( "255.255.255.255" ) // ["255.255.255.255", "255", "255", "255", "255"]
rip2.exec( "256.255.255.255" ) // null