How use the RegExp to filter IP address in js All In One
如何使用 RegExp 在 js 中过滤 IP 地址
192.168.18.1 < 192.168.18.N
< 192.168.18.255
ignore IPs: 192.168.18.0
/ 192.168.18.1
/ 192.168.18.255
error
function test(n) {
let reg = /192\.168\.(1?[0-9][0-9]|2[0-5][0-5])\.(1?[0-9]?[1-9]|2[0-4][0-9]|25[0-4])/;
for (let i = 0; i < n; i++) {
let result = reg.test(`192.168.18.${i}`);
if(result) {
// console.log(`192.168.18.${i} ✅`, i, result)
} else {
console.log(`192.168.18.${i} ❌`, i, result)
}
}
}
test(256);
// 192.168.18.0 ❌ 0 false
reg = /192\.168\.(25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[2-9])/;
reg.test(`192.168.0`);
false
reg.test(`192.168.1`);
false
reg.test(`192.168.2`);
true
reg.test(`192.168.254`);
true
reg.test(`192.168.255`);
true
solution
$
for end ✅
reg = /192\.168\.(25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[2-9])$/;
reg.test(`192.168.0`);
false
reg.test(`192.168.1`);
false
reg.test(`192.168.2`);
true
reg.test(`192.168.254`);
true
reg.test(`192.168.255`);
true
Regexper
# no end ❌
reg = /192\.168\.(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([2-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])/;
# `$` end ✅
reg = /192\.168\.(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([2-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])$/;
demos
function test(n) {
let reg = /192\.168\.(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([2-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])$/;
for (let i = 0; i < n; i++) {
let result = reg.test(`192.168.18.${i}`);
if(result) {
// console.log(`192.168.18.${i} ✅`, i, result)
} else {
console.log(`192.168.18.${i} ❌`, i, result)
}
}
}
test(256);
192.168.18.0 ❌ 0 false
192.168.18.1 ❌ 1 false
192.168.18.255 ❌ 255 false