[英]regular expression for ip v4
I am doing an ip v4 validator program with javascript. 我正在使用javascript做IP v4验证程序。 The ip has to be between the range of
1.0.0.0
to 255.255.255.255
My problem is that I also get the 0.0.0.0
and should not take it. IP必须在
1.0.0.0
到255.255.255.255
的范围之间。我的问题是我也得到了0.0.0.0
,因此不应使用它。
I leave you my regular expression: 我给你我的正则表达式:
Var Expression1 = new RegExp ("[0-9] | [1-9] [0-9] | 1 [0-9] {2} | 2 [0-4] [0-9] | 25 [0-5]) [3] ([0-9] | [1-9] [0-9] | 1 [0-9] {2} | 2 [0-4] [0-9] ] | 25 [0-5]) $ ");
Thank you! 谢谢!
Add "not 0.0.0.0" negative lookbehind ( ^(?!0\\.0\\.0\\.0)
) at the beginning of the line: 在行的开头添加“ not 0.0.0.0”负向后(
^(?!0\\.0\\.0\\.0)
):
^(?!0\.0\.0\.0)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$
Demo: https://regex101.com/r/dIkHRJ/2 演示: https : //regex101.com/r/dIkHRJ/2
PS PS
Please notice your regex is incomplete and broken. 请注意您的正则表达式不完整且已损坏。 Use the corrected one from the sample above.
使用上面的示例中更正的一个。
Why not use a function, it will be clearer not using a regex: 为什么不使用函数,不使用正则表达式会更清楚:
function validateIP(ip) { var p = ip.split('.'); // split it by '.' if(p.length !== 4) return false; // if there is not for parts => false for(var i = 0; i < 4; i++) // for each part if(isNaN(p[i]) || i < 0 || i > 255) return false; // if it's not a number between 0 - 255 => false return p[3] > 0; // return true if the last part is not 0, false otherwise } alert(validateIP(prompt("IP: ")));
The more accurate solution using RegExp.prototype.test()
, String.prototype.split()
and Array.prototype.every()
functions: 使用
RegExp.prototype.test()
, String.prototype.split()
和Array.prototype.every()
函数的更准确的解决方案:
var re = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/, validateIPv4 = function(ip) { return re.test(ip) && ip.split('.').every(function(d, idx){ var octet = Number(d); if (idx === 0) { return octet > 0; } return 0 <= octet && octet <= 255; }); }; console.log(validateIPv4('0.0.0.0')); console.log(validateIPv4('1.0.0.0')); console.log(validateIPv4('127.0.0.1')); console.log(validateIPv4('255.255.255.255'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.