javascript正则表达式检查IP地址

发布于 2024-10-07 22:22:25 字数 347 浏览 5 评论 0原文

我有几个IP地址,例如:

  1. 115.42.150.37
  2. 115.42.150.38
  3. 115.42.150.50

如果我想搜索,我应该写什么类型的正则表达式对于所有 3 个 IP 地址?例如,如果我执行 115.42.150.* (我将能够搜索所有 3 个 IP 地址),

我现在可以做的是: /[0-9]{1 -3}\.[0-9]{1-3}\.[0-9]{1-3}\.[0-9]{1-3}/ 但似乎不能好好工作。

谢谢。

I have several ip addresses like:

  1. 115.42.150.37
  2. 115.42.150.38
  3. 115.42.150.50

What type of regular expression should I write if I want to search for the all the 3 ip addresses? Eg, if I do 115.42.150.* (I will be able to search for all 3 ip addresses)

What I can do now is something like: /[0-9]{1-3}\.[0-9]{1-3}\.[0-9]{1-3}\.[0-9]{1-3}/ but it can't seems to work well.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(27

爱的那么颓废 2024-10-14 22:22:29

除了没有正则表达式的解决方案之外:

const checkValidIpv4 = (entry) => {
  const mainPipeline = [
    block => !isNaN(parseInt(block, 10)),
    block => parseInt(block,10) >= 0,
    block => parseInt(block,10) <= 255,
    block => String(block).length === 1
      || String(block).length > 1
      && String(block)[0] !== '0',
  ];

  const blocks = entry.split(".");
  if(blocks.length === 4
    && !blocks.every(block => parseInt(block, 10) === 0)) {
    return blocks.every(block =>
      mainPipeline.every(ckeck => ckeck(block) )
    );
  }

  return false;
}

console.log(checkValidIpv4('0.0.0.0')); //false
console.log(checkValidIpv4('0.0.0.1')); //true
console.log(checkValidIpv4('0.01.001.0')); //false
console.log(checkValidIpv4('8.0.8.0')); //true

In addition to a solution without regex:

const checkValidIpv4 = (entry) => {
  const mainPipeline = [
    block => !isNaN(parseInt(block, 10)),
    block => parseInt(block,10) >= 0,
    block => parseInt(block,10) <= 255,
    block => String(block).length === 1
      || String(block).length > 1
      && String(block)[0] !== '0',
  ];

  const blocks = entry.split(".");
  if(blocks.length === 4
    && !blocks.every(block => parseInt(block, 10) === 0)) {
    return blocks.every(block =>
      mainPipeline.every(ckeck => ckeck(block) )
    );
  }

  return false;
}

console.log(checkValidIpv4('0.0.0.0')); //false
console.log(checkValidIpv4('0.0.0.1')); //true
console.log(checkValidIpv4('0.01.001.0')); //false
console.log(checkValidIpv4('8.0.8.0')); //true

你丑哭了我 2024-10-14 22:22:29

这应该有效:

function isValidIP(str) {
  const arr = str.split(".").filter((el) => {
    return !/^0.|\D/g.test(el);
  });

  return arr.filter((el) => el.length && el >= 0 && el <= 255).length === 4;
}

This should work:

function isValidIP(str) {
  const arr = str.split(".").filter((el) => {
    return !/^0.|\D/g.test(el);
  });

  return arr.filter((el) => el.length && el >= 0 && el <= 255).length === 4;
}
惯饮孤独 2024-10-14 22:22:29

总是寻找变化,似乎是一项重复性的任务,所以使用 forEach 怎么样!

function checkIP(ip) {
  //assume IP is valid to start, once false is found, always false
  var test = true;

  //uses forEach method to test each block of IPv4 address
  ip.split('.').forEach(validateIP4);

  if (!test) 
    alert("Invalid IP4 format\n"+ip) 
  else 
    alert("IP4 format correct\n"+ip);

  function validateIP4(num, index, arr) {
    //returns NaN if not an Int
    item = parseInt(num, 10);
    //test validates Int, 0-255 range and 4 bytes of address
    // && test; at end required because this function called for each block
    test = !isNaN(item) && !isNaN(num) && item >=0 && item < 256 && arr.length==4 && test;
  }
}

Always looking for variations, seemed to be a repetitive task so how about using forEach!

function checkIP(ip) {
  //assume IP is valid to start, once false is found, always false
  var test = true;

  //uses forEach method to test each block of IPv4 address
  ip.split('.').forEach(validateIP4);

  if (!test) 
    alert("Invalid IP4 format\n"+ip) 
  else 
    alert("IP4 format correct\n"+ip);

  function validateIP4(num, index, arr) {
    //returns NaN if not an Int
    item = parseInt(num, 10);
    //test validates Int, 0-255 range and 4 bytes of address
    // && test; at end required because this function called for each block
    test = !isNaN(item) && !isNaN(num) && item >=0 && item < 256 && arr.length==4 && test;
  }
}
凉城 2024-10-14 22:22:29

好吧,我尝试这个,我考虑了案例以及条目必须如何:

function isValidIP(str) {
   let cong= /^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/  
   return cong.test(str);}

well I try this, I considered cases and how the entries had to be:

function isValidIP(str) {
   let cong= /^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/  
   return cong.test(str);}
假情假意假温柔 2024-10-14 22:22:29

用于验证一致 IP 地址的正则表达式

/^(25[0-4]|2[0-4]\d|1(\d{2})|[1-9]\d|[1-9])(\.(25[0-4]|2[0-4]\d|1(\d{2})|[1-9]\d|\d)){3}$/

示例:

const ipArr = ['\\\\115.42.150.37\\', '\\\\192.168.0.1\\', '   \\\\66.88.3', '\\\\110.234.52.124\\', '\\\\Z:\\'];

const getIpHost = (ip) => {
  if (ip) {
    const hostPortArr = ip.replace(/\\/g, '').split(':');
    return (hostPortArr[0] || '').trim();
  }
  return '';
}

const validateIp = (ip) => {
  if (!ip?.trim().length) {
    return false;
  }

  const ipAdr = getIpHost(ip);
  const regExp = /^(25[0-4]|2[0-4]\d|1(\d{2})|[1-9]\d|[1-9])(\.(25[0-4]|2[0-4]\d|1(\d{2})|[1-9]\d|\d)){3}$/;
  return regExp.test(ipAdr);
}

ipArr.forEach((ip) => {
  const isValid = validateIp(ip);
  console.log(`${ip}:`, isValid)
})

控制台输出:

\\115.42.150.37\: true
\\192.168.0.1\: true
   \\66.88.3: false
\\110.234.52.124\: true
\\Z:\: false

A regular expression for validate well conformed ip address

/^(25[0-4]|2[0-4]\d|1(\d{2})|[1-9]\d|[1-9])(\.(25[0-4]|2[0-4]\d|1(\d{2})|[1-9]\d|\d)){3}$/

Example:

const ipArr = ['\\\\115.42.150.37\\', '\\\\192.168.0.1\\', '   \\\\66.88.3', '\\\\110.234.52.124\\', '\\\\Z:\\'];

const getIpHost = (ip) => {
  if (ip) {
    const hostPortArr = ip.replace(/\\/g, '').split(':');
    return (hostPortArr[0] || '').trim();
  }
  return '';
}

const validateIp = (ip) => {
  if (!ip?.trim().length) {
    return false;
  }

  const ipAdr = getIpHost(ip);
  const regExp = /^(25[0-4]|2[0-4]\d|1(\d{2})|[1-9]\d|[1-9])(\.(25[0-4]|2[0-4]\d|1(\d{2})|[1-9]\d|\d)){3}$/;
  return regExp.test(ipAdr);
}

ipArr.forEach((ip) => {
  const isValid = validateIp(ip);
  console.log(`${ip}:`, isValid)
})

Console Output:

\\115.42.150.37\: true
\\192.168.0.1\: true
   \\66.88.3: false
\\110.234.52.124\: true
\\Z:\: false
拔了角的鹿 2024-10-14 22:22:29

这就是我在 May 代码中使用 IP 地址验证的方式,并且它工作正常。

if (!ipaddress.match(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/)) {
 alert("Invalid Ip Address");
 return;
}

this is how i used ip address validation for may code, and it is working properly.

if (!ipaddress.match(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/)) {
 alert("Invalid Ip Address");
 return;
}
我们的影子 2024-10-14 22:22:29

对于那些尝试验证 IPv4 和 IPv6 的人,以下代码片段利用了 @Spudley 的简洁答案。

const isValidIPv4 = (ip) => {
    const blocks = ip.split('.');
    if (blocks.length !== 4) {
        return false;
    }
    for (const block of blocks) {
        const numericBlock = parseInt(block, 10);
        if (!(numericBlock >= 0 && numericBlock <= 255)) {
            return false; 
        }
    }
    return true;
}
const isValidIPv6 = (ip) => {
    const blocks = ip.split(':');
    if (blocks.length < 8) {
        return false;
    }
    for (const block of blocks) {
        if (!/^[0-9A-Fa-f]{1,4}$/.test(block)) {
            return false; 
        }
    }
    return true;
}
const isValidIP = (ip) => {
    return isValidIPv4(ip) || isValidIPv6(ip);
}

谢谢 @Spudley

For those trying to validate IPv4 and IPv6, the following snippet makes use of @Spudley's concise answer..

const isValidIPv4 = (ip) => {
    const blocks = ip.split('.');
    if (blocks.length !== 4) {
        return false;
    }
    for (const block of blocks) {
        const numericBlock = parseInt(block, 10);
        if (!(numericBlock >= 0 && numericBlock <= 255)) {
            return false; 
        }
    }
    return true;
}
const isValidIPv6 = (ip) => {
    const blocks = ip.split(':');
    if (blocks.length < 8) {
        return false;
    }
    for (const block of blocks) {
        if (!/^[0-9A-Fa-f]{1,4}$/.test(block)) {
            return false; 
        }
    }
    return true;
}
const isValidIP = (ip) => {
    return isValidIPv4(ip) || isValidIPv6(ip);
}

Thank you @Spudley

北方。的韩爷 2024-10-14 22:22:29

测试类型而不是有效性时不太严格。例如,当对列进行排序时,使用此检查来查看要使用哪种排序。

export const isIpAddress = (ipAddress) => 
    /^((\d){1,3}\.){3}(\d){1,3}$/.test(ipAddress)

检查有效性时使用此测试。更严格的测试检查 IP 8 位数字是否在 0-255 范围内:

export const isValidIpAddress = (ipAddress) => 
    /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipAddress)

A less stringent when testing the type not the validity. For example when sorting columns use this check to see which sort to use.

export const isIpAddress = (ipAddress) => 
    /^((\d){1,3}\.){3}(\d){1,3}$/.test(ipAddress)

When checking for validity use this test. An even more stringent test checking that the IP 8-bit numbers are in the range 0-255:

export const isValidIpAddress = (ipAddress) => 
    /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipAddress)
星星的轨迹 2024-10-14 22:22:28

这就是我所做的,它速度快且工作完美:

function isIPv4Address(inputString) {
    let regex = new RegExp(/^(([0-9]{1,3}\.){3}[0-9]{1,3})$/);
    if(regex.test(inputString)){
        let arInput = inputString.split(".")
        for(let i of arInput){
            if(i.length > 1 && i.charAt(0) === '0')
                return false;
            else{
                if(parseInt(i) < 0 || parseInt(i) >=256)
                   return false;
            }
        }
    }
    else
        return false;
    return true;
}

说明:首先,使用正则表达式检查 IP 格式是否正确。尽管如此,正则表达式不会检查任何值范围。

我的意思是,如果你可以使用 Javascript 来管理正则表达式,为什么不使用它呢?因此,不要使用疯狂的正则表达式,而应仅使用正则表达式来检查格式是否正确,然后检查八位位组中的每个值是否在正确的值范围内(0 到 255)。希望这对其他人有帮助。和平。

This is what I did and it's fast and works perfectly:

function isIPv4Address(inputString) {
    let regex = new RegExp(/^(([0-9]{1,3}\.){3}[0-9]{1,3})$/);
    if(regex.test(inputString)){
        let arInput = inputString.split(".")
        for(let i of arInput){
            if(i.length > 1 && i.charAt(0) === '0')
                return false;
            else{
                if(parseInt(i) < 0 || parseInt(i) >=256)
                   return false;
            }
        }
    }
    else
        return false;
    return true;
}

Explanation: First, with the regex check that the IP format is correct. Although, the regex won't check any value ranges.

I mean, if you can use Javascript to manage regex, why not use it?. So, instead of using a crazy regex, use Regex only for checking that the format is fine and then check that each value in the octet is in the correct value range (0 to 255). Hope this helps anybody else. Peace.

嘴硬脾气大 2024-10-14 22:22:28

而不是

{1-3}

你应该放

{1,3}

And instead of

{1-3}

you should put

{1,3}
千秋岁 2024-10-14 22:22:28
\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b

匹配 0.0.0.0 到 999.999.999.999
如果您知道 seachdata 不包含无效 IP 地址,

\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b

则使用 用于准确匹配 IP 号码 - 4 个号码中的每一个都存储到它自己的捕获组中,以便您稍后可以访问它们

\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b

matches 0.0.0.0 through 999.999.999.999
use if you know the seachdata does not contain invalid IP addresses

\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b

use to match IP numbers with accurracy - each of the 4 numbers is stored into it's own capturing group, so you can access them later

策马西风 2024-10-14 22:22:28

也许更好:

function checkIP(ip) {
    var x = ip.split("."), x1, x2, x3, x4;

    if (x.length == 4) {
        x1 = parseInt(x[0], 10);
        x2 = parseInt(x[1], 10);
        x3 = parseInt(x[2], 10);
        x4 = parseInt(x[3], 10);

        if (isNaN(x1) || isNaN(x2) || isNaN(x3) || isNaN(x4)) {
            return false;
        }

        if ((x1 >= 0 && x1 <= 255) && (x2 >= 0 && x2 <= 255) && (x3 >= 0 && x3 <= 255) && (x4 >= 0 && x4 <= 255)) {
            return true;
        }
    }
    return false;
}    

it is maybe better:

function checkIP(ip) {
    var x = ip.split("."), x1, x2, x3, x4;

    if (x.length == 4) {
        x1 = parseInt(x[0], 10);
        x2 = parseInt(x[1], 10);
        x3 = parseInt(x[2], 10);
        x4 = parseInt(x[3], 10);

        if (isNaN(x1) || isNaN(x2) || isNaN(x3) || isNaN(x4)) {
            return false;
        }

        if ((x1 >= 0 && x1 <= 255) && (x2 >= 0 && x2 <= 255) && (x3 >= 0 && x3 <= 255) && (x4 >= 0 && x4 <= 255)) {
            return true;
        }
    }
    return false;
}    
半边脸i 2024-10-14 22:22:28

答案允许 IP 地址中存在前导零,但这是不正确的。
例如(“123.045.067.089”应返回 false)。

正确的方法就是这样做。

 function isValidIP(ipaddress) {  
if (/^(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)$/.test(ipaddress)) {  
  return (true)  
}   
return (false) } 

此函数不允许以零开头的 IP 地址。

The answers over allow leading zeros in Ip address, and that it is not correct.
For example ("123.045.067.089"should return false).

The correct way to do it like that.

 function isValidIP(ipaddress) {  
if (/^(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)$/.test(ipaddress)) {  
  return (true)  
}   
return (false) } 

This function will not allow zero to lead IP addresses.

与风相奔跑 2024-10-14 22:22:27

不要编写自己的正则表达式或复制粘贴!您可能不会涵盖所有边缘情况(IPv6,还有八进制 IP 等)。使用 npm 中的 is-ip

var isIp = require('is-ip');

isIp('192.168.0.1');

isIp('1:2:3:4:5:6:7:8');

将返回一个布尔值。

Don't write your own regex or copy paste! You probably won't cover all edge cases (IPv6, but also octal IPs, etc). Use the is-ip package from npm:

var isIp = require('is-ip');

isIp('192.168.0.1');

isIp('1:2:3:4:5:6:7:8');

Will return a Boolean.

悍妇囚夫 2024-10-14 22:22:27

试试这个。来源来自此处

"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"

Try this one.. Source from here.

"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
变身佩奇 2024-10-14 22:22:27

下面的解决方案不接受填充零

这是验证 IP 地址的最简洁方法,让我们对其进行分解:

事实:有效的 IP 地址有 4八位字节,每个八位字节可以是 0 - 255 之间的数字

匹配 0 - 255 之间任何值的正则表达式细分

  • 25[0-5] 匹配 250 - 255
  • 2[0-4][0-9] 匹配 200 - 249
  • 1[0 -9][0-9] 匹配 100 - 199
  • [1-9][0-9]? 匹配 1 - 99 code>
  • 0 匹配 0
const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';

注释: 使用 new RegExp 时,应使用 \\. 而不是 \. 因为字符串会被转义两次。

function isValidIP(str) {
  const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';
  const regex = new RegExp(`^${octet}\\.${octet}\\.${octet}\\.${octet}

下面的解决方案不接受填充零

这是验证 IP 地址的最简洁方法,让我们对其进行分解:

事实:有效的 IP 地址有 4八位字节,每个八位字节可以是 0 - 255 之间的数字

匹配 0 - 255 之间任何值的正则表达式细分

  • 25[0-5] 匹配 250 - 255
  • 2[0-4][0-9] 匹配 200 - 249
  • 1[0 -9][0-9] 匹配 100 - 199
  • [1-9][0-9]? 匹配 1 - 99 code>
  • 0 匹配 0
const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';

注释: 使用 new RegExp 时,应使用 \\. 而不是 \. 因为字符串会被转义两次。

); return regex.test(str); }

Below Solution doesn't accept Padding Zeros

Here is the cleanest way to validate an IP Address, Let's break it down:

Fact: a valid IP Address is has 4 octets, each octets can be a number between 0 - 255

Breakdown of Regex that matches any value between 0 - 255

  • 25[0-5] matches 250 - 255
  • 2[0-4][0-9] matches 200 - 249
  • 1[0-9][0-9] matches 100 - 199
  • [1-9][0-9]? matches 1 - 99
  • 0 matches 0
const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';

Notes: When using new RegExp you should use \\. instead of \. since string will get escaped twice.

function isValidIP(str) {
  const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';
  const regex = new RegExp(`^${octet}\\.${octet}\\.${octet}\\.${octet}

Below Solution doesn't accept Padding Zeros

Here is the cleanest way to validate an IP Address, Let's break it down:

Fact: a valid IP Address is has 4 octets, each octets can be a number between 0 - 255

Breakdown of Regex that matches any value between 0 - 255

  • 25[0-5] matches 250 - 255
  • 2[0-4][0-9] matches 200 - 249
  • 1[0-9][0-9] matches 100 - 199
  • [1-9][0-9]? matches 1 - 99
  • 0 matches 0
const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';

Notes: When using new RegExp you should use \\. instead of \. since string will get escaped twice.

); return regex.test(str); }
携余温的黄昏 2024-10-14 22:22:27

如果您想要在现代浏览器中比 ipv4 的正则表达式更具可读性的东西,您可以使用

function checkIsIPV4(entry) {
  var blocks = entry.split(".");
  if(blocks.length === 4) {
    return blocks.every(function(block) {
      return parseInt(block,10) >=0 && parseInt(block,10) <= 255;
    });
  }
  return false;
}

If you want something more readable than regex for ipv4 in modern browsers you can go with

function checkIsIPV4(entry) {
  var blocks = entry.split(".");
  if(blocks.length === 4) {
    return blocks.every(function(block) {
      return parseInt(block,10) >=0 && parseInt(block,10) <= 255;
    });
  }
  return false;
}
有深☉意 2024-10-14 22:22:27

一个简短的正则表达式: ^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d) ){4}$

示例

const isValidIp = value => (/^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$/.test(value));


// valid
console.log("isValidIp('0.0.0.0') ? ", isValidIp('0.0.0.0'));
console.log("isValidIp('115.42.150.37') ? ", isValidIp('115.42.150.37'));
console.log("isValidIp('192.168.0.1') ? ", isValidIp('192.168.0.1'));
console.log("isValidIp('110.234.52.124') ? ", isValidIp('110.234.52.124'));
console.log("isValidIp('115.42.150.37') ? ", isValidIp('115.42.150.37'));
console.log("isValidIp('115.42.150.38') ? ", isValidIp('115.42.150.38'));
console.log("isValidIp('115.42.150.50') ? ", isValidIp('115.42.150.50'));
console.log("isValidIp('192.168.1.70') ? ", isValidIp('192.168.1.70'));

// Invalid
console.log("isValidIp('210.110') ? ", isValidIp('210.110'));
console.log("isValidIp('255') ? ", isValidIp('255'));
console.log("isValidIp('y.y.y.y') ? ", isValidIp('y.y.y.y'));
console.log("isValidIp('255.0.0.y') ? ", isValidIp('255.0.0.y'));
console.log("isValidIp('666.10.10.20') ? ", isValidIp('666.10.10.20'));
console.log("isValidIp('4444.11.11.11') ? ", isValidIp('4444.11.11.11'));
console.log("isValidIp('33.3333.33.3') ? ", isValidIp('33.3333.33.3'));
console.log("isValidIp('0192.168.1.70') ? ", isValidIp('0192.168.1.70'));

A short RegEx: ^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$

Example

const isValidIp = value => (/^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$/.test(value));


// valid
console.log("isValidIp('0.0.0.0') ? ", isValidIp('0.0.0.0'));
console.log("isValidIp('115.42.150.37') ? ", isValidIp('115.42.150.37'));
console.log("isValidIp('192.168.0.1') ? ", isValidIp('192.168.0.1'));
console.log("isValidIp('110.234.52.124') ? ", isValidIp('110.234.52.124'));
console.log("isValidIp('115.42.150.37') ? ", isValidIp('115.42.150.37'));
console.log("isValidIp('115.42.150.38') ? ", isValidIp('115.42.150.38'));
console.log("isValidIp('115.42.150.50') ? ", isValidIp('115.42.150.50'));
console.log("isValidIp('192.168.1.70') ? ", isValidIp('192.168.1.70'));

// Invalid
console.log("isValidIp('210.110') ? ", isValidIp('210.110'));
console.log("isValidIp('255') ? ", isValidIp('255'));
console.log("isValidIp('y.y.y.y') ? ", isValidIp('y.y.y.y'));
console.log("isValidIp('255.0.0.y') ? ", isValidIp('255.0.0.y'));
console.log("isValidIp('666.10.10.20') ? ", isValidIp('666.10.10.20'));
console.log("isValidIp('4444.11.11.11') ? ", isValidIp('4444.11.11.11'));
console.log("isValidIp('33.3333.33.3') ? ", isValidIp('33.3333.33.3'));
console.log("isValidIp('0192.168.1.70') ? ", isValidIp('0192.168.1.70'));

沫离伤花 2024-10-14 22:22:27
/^(?!.*\.$)((?!0\d)(1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/

完全归功于 oriadam。我会在他/她的答案下面评论以建议我所做的双零更改,但我在这里还没有足够的声誉...

更改

  • -(?!0) 因为 IPv4以零 ('0.248.42.223') 开头的地址是有效但不是可用)

  • +(?!0\d) 因为带有前导零的 IPv4 地址(“63.14.209.00”和“011.012.013.014”)有时可以解释为八进制

/^(?!.*\.$)((?!0\d)(1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/

Full credit to oriadam. I would have commented below his/her answer to suggest the double zero change I made, but I do not have enough reputation here yet...

change:

相思故 2024-10-14 22:22:27

简单方法

const invalidIp = ipAddress
   .split(".")
   .map(ip => Number(ip) >= 0 && Number(ip) <= 255)
   .includes(false);

if(invalidIp){
 // IP address is invalid
 // throw error here
}

Simple Method

const invalidIp = ipAddress
   .split(".")
   .map(ip => Number(ip) >= 0 && Number(ip) <= 255)
   .includes(false);

if(invalidIp){
 // IP address is invalid
 // throw error here
}
佼人 2024-10-14 22:22:27

IP地址格式的正则表达式:

/^(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])\.(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])\.(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])$/;

Regular expression for the IP address format:

/^(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])\.(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])\.(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])$/;
扶醉桌前 2024-10-14 22:22:27

如果您编写正确的代码,您只需要这个非常简单的正则表达式: /\d{1,3}/

function isIP(ip) {
    let arrIp = ip.split(".");
    if (arrIp.length !== 4) return "Invalid IP";
    let re = /\d{1,3}/;
    for (let oct of arrIp) {
        if (oct.match(re) === null) return "Invalid IP"
        if (Number(oct) < 0 || Number(oct) > 255)
            return "Invalid IP";
}
    return "Valid IP";
}

但实际上,您根本不使用任何正则表达式,可以获得更简单的代码:

function isIp(ip) {
    var arrIp = ip.split(".");
    if (arrIp.length !== 4) return "Invalid IP";
    for (let oct of arrIp) {
        if ( isNaN(oct) || Number(oct) < 0 || Number(oct) > 255)
            return "Invalid IP";
}
    return "Valid IP";
}

If you wrtie the proper code you need only this very simple regular expression: /\d{1,3}/

function isIP(ip) {
    let arrIp = ip.split(".");
    if (arrIp.length !== 4) return "Invalid IP";
    let re = /\d{1,3}/;
    for (let oct of arrIp) {
        if (oct.match(re) === null) return "Invalid IP"
        if (Number(oct) < 0 || Number(oct) > 255)
            return "Invalid IP";
}
    return "Valid IP";
}

But actually you get even simpler code by not using any regular expression at all:

function isIp(ip) {
    var arrIp = ip.split(".");
    if (arrIp.length !== 4) return "Invalid IP";
    for (let oct of arrIp) {
        if ( isNaN(oct) || Number(oct) < 0 || Number(oct) > 255)
            return "Invalid IP";
}
    return "Valid IP";
}
耳钉梦 2024-10-14 22:22:27

添加迟到的贡献:

^(?!\.)((^|\.)([1-9]?\d|1\d\d|2(5[0-5]|[0-4]\d))){4}$

在我检查的答案中,它们的验证要么更长,要么不完整。根据我的经验,更长的时间意味着更难被忽视,因此更容易出错。出于同样的原因,我喜欢避免重复类似的模式。

当然,主要部分是对数字的测试 - 0 到 255,但也要确保它不允许初始零(除非它是单个零):

[1-9]?\d|1\d\d|2(5[0-5]|[0-4]\d)

三种交替 - 一种用于 100 以下: [1-9]?\d,100-199:1\d\d 最后是 200-255:2(5[0-5]|[ 0-4]\d)

在此之前是对行首 .的测试,并且整个表达式由附加的测试了4次>{4}

对四字节表示的完整测试首先测试行首,然后进行负向预测以避免以 . 开头的地址:^(?!\.) ,并以行尾测试 ($) 结束。

在 regex101 上查看一些示例。

Throwing in a late contribution:

^(?!\.)((^|\.)([1-9]?\d|1\d\d|2(5[0-5]|[0-4]\d))){4}$

Of the answers I checked, they're either longer or incomplete in their verification. Longer, in my experience, means harder to overlook and therefore more prone to be erroneous. And I like to avoid repeating similar patters, for the same reason.

The main part is, of course, the test for a number - 0 to 255, but also making sure it doesn't allow initial zeroes (except for when it's a single one):

[1-9]?\d|1\d\d|2(5[0-5]|[0-4]\d)

Three alternations - one for sub 100: [1-9]?\d, one for 100-199: 1\d\d and finally 200-255: 2(5[0-5]|[0-4]\d).

This is preceded by a test for start of line or a dot ., and this whole expression is tested for 4 times by the appended {4}.

This complete test for four byte representations is started by testing for start of line followed by a negative look ahead to avoid addresses starting with a .: ^(?!\.), and ended with a test for end of line ($).

See some samples here at regex101.

停顿的约定 2024-10-14 22:22:26

可能会迟到,但有人可以尝试:

有效 IP 地址示例

115.42.150.37
192.168.0.1
110.234.52.124

无效 IP 地址示例

210.110 – must have 4 octets
255 – must have 4 octets
y.y.y.y – only digits are allowed
255.0.0.y – only digits are allowed
666.10.10.20 – octet number must be between [0-255]
4444.11.11.11 – octet number must be between [0-255]
33.3333.33.3 – octet number must be between [0-255]

用于验证 IP 地址的 JavaScript 代码

function ValidateIPaddress(ipaddress) {  
  if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress)) {  
    return (true)  
  }  
  alert("You have entered an invalid IP address!")  
  return (false)  
}  

May be late but, someone could try:

Example of VALID IP address

115.42.150.37
192.168.0.1
110.234.52.124

Example of INVALID IP address

210.110 – must have 4 octets
255 – must have 4 octets
y.y.y.y – only digits are allowed
255.0.0.y – only digits are allowed
666.10.10.20 – octet number must be between [0-255]
4444.11.11.11 – octet number must be between [0-255]
33.3333.33.3 – octet number must be between [0-255]

JavaScript code to validate an IP address

function ValidateIPaddress(ipaddress) {  
  if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress)) {  
    return (true)  
  }  
  alert("You have entered an invalid IP address!")  
  return (false)  
}  
谜泪 2024-10-14 22:22:26

试试这个,它是一个较短的版本:

^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$

解释:

^ start of string
  (?!0)         Assume IP cannot start with 0
  (?!.*\.$)     Make sure string does not end with a dot
  (
    (
    1?\d?\d|   A single digit, two digits, or 100-199
    25[0-5]|   The numbers 250-255
    2[0-4]\d   The numbers 200-249
    )
  \.|$ the number must be followed by either a dot or end-of-string - to match the last number
  ){4}         Expect exactly four of these
$ end of string

浏览器控制台的单元测试:

var rx=/^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/;
var valid=['1.2.3.4','11.11.11.11','123.123.123.123','255.250.249.0','1.12.123.255','127.0.0.1','1.0.0.0'];
var invalid=['0.1.1.1','01.1.1.1','012.1.1.1','1.2.3.4.','1.2.3\n4','1.2.3.4\n','259.0.0.1','123.','1.2.3.4.5','.1.2.3.4','1,2,3,4','1.2.333.4','1.299.3.4'];
valid.forEach(function(s){if (!rx.test(s))console.log('bad valid: '+s);});
invalid.forEach(function(s){if (rx.test(s)) console.log('bad invalid: '+s);});

Try this one, it's a shorter version:

^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$

Explained:

^ start of string
  (?!0)         Assume IP cannot start with 0
  (?!.*\.$)     Make sure string does not end with a dot
  (
    (
    1?\d?\d|   A single digit, two digits, or 100-199
    25[0-5]|   The numbers 250-255
    2[0-4]\d   The numbers 200-249
    )
  \.|$ the number must be followed by either a dot or end-of-string - to match the last number
  ){4}         Expect exactly four of these
$ end of string

Unit test for a browser's console:

var rx=/^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/;
var valid=['1.2.3.4','11.11.11.11','123.123.123.123','255.250.249.0','1.12.123.255','127.0.0.1','1.0.0.0'];
var invalid=['0.1.1.1','01.1.1.1','012.1.1.1','1.2.3.4.','1.2.3\n4','1.2.3.4\n','259.0.0.1','123.','1.2.3.4.5','.1.2.3.4','1,2,3,4','1.2.333.4','1.299.3.4'];
valid.forEach(function(s){if (!rx.test(s))console.log('bad valid: '+s);});
invalid.forEach(function(s){if (rx.test(s)) console.log('bad invalid: '+s);});
来日方长 2024-10-14 22:22:26

如果您使用的是nodejs,请尝试:

require('net').isIP('10.0.0.1')

doc net.isIP()

If you are using nodejs try:

require('net').isIP('10.0.0.1')

doc net.isIP()

笔芯 2024-10-14 22:22:26

您获得的正则表达式已经存在几个问题:

首先,它包含点。在正则表达式中,点表示“匹配任何字符”,您只需匹配实际的点。为此,您需要转义它,因此在点前面放一个反斜杠。

其次,但您要匹配每个部分中的任意三个数字。这意味着您将匹配 0 到 999 之间的任何数字,这显然包含许多无效的 IP 地址数字。

这可以通过使号码匹配更复杂来解决;该网站上还有其他答案解释了如何做到这一点,但坦率地说,这不值得付出努力——在我看来,最好将字符串按点分开,然后将四个块验证为数字整数范围——即:

if(block >= 0 && block <= 255) {....}

希望有帮助。

The regex you've got already has several problems:

Firstly, it contains dots. In regex, a dot means "match any character", where you need to match just an actual dot. For this, you need to escape it, so put a back-slash in front of the dots.

Secondly, but you're matching any three digits in each section. This means you'll match any number between 0 and 999, which obviously contains a lot of invalid IP address numbers.

This can be solved by making the number matching more complex; there are other answers on this site which explain how to do that, but frankly it's not worth the effort -- in my opinion, you'd be much better off splitting the string by the dots, and then just validating the four blocks as numeric integer ranges -- ie:

if(block >= 0 && block <= 255) {....}

Hope that helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文