Javascript IP 地址验证的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10006459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:26:52  来源:igfitidea点击:

Regular expression for IP Address Validation

javascriptregex

提问by Manikandan Sethuraju

i want to validate the value is valid IP Address or not..!

我想验证该值是否为有效的 IP 地址..!

I Used to validate like

我曾经验证过

ValidIpAddressRegex = "^(([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])$";

it's working fine, but when i give the values like 12345678, its also return true.. How to solve this?

它工作正常,但是当我给出类似的值时12345678,它也返回true.. 如何解决这个问题?

回答by Colin Hebert

There is a simpler way. You just need to split the string on .and check that every number is between 0 and 255.

有一个更简单的方法。您只需要拆分字符串.并检查每个数字是否在 0 到 255 之间。

Additionally, you can check for hexa and split on :for IPv6.

此外,您可以检查 hexa 并拆分:IPv6。



Just because I think it's funny:

只是因为我觉得这很有趣:

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

Here is a regex that should handle IPs (v4).

这是一个应该处理 IP (v4) 的正则表达式。

回答by ohaal

Looking for one for IPv4, I ended up just creating it myself. (This only handles the common dotted variant, i.e. 0.0.0.0 - 255.255.255.255)

为 IPv4 寻找一个,我最终只是自己创建了它。(这仅处理常见的虚线变体,即 0.0.0.0 - 255.255.255.255)

^                           # START OF STRING
  (?=\d+\.\d+\.\d+\.\d+$)     # Lookahead, require this format: number.number.number.number END OF STRING
  (?:                         # Start non-capture group (number 0-255 + optional dot)
    (?:                         # Start non-capture group (number 0-255)
      25[0-5]                     # 250-255
      |                           # OR
      2[0-4][0-9]                 # 200-249
      |                           # OR
      1[0-9]{2}                   # 100-199
      |                           # OR
      [1-9][0-9]                  # 10-99
      |                           # OR
      [0-9]                       # 0-9
    )                           # End non-capture group
    \.?                         # Optional dot (enforced in correct positions by lookahead)
  ){4}                        # End non-capture group (number + optional dot), repeat 4 times
$                           # END OF STRING

Without comments:

没有评论:

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

Some code to test it:

一些代码来测试它:

function isValidIpv4Addr(ip) {
  return /^(?=\d+\.\d+\.\d+\.\d+$)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.?){4}$/.test(ip);
}
var testAddr = ['192.68.35.35','0.0.0.0','255.0.0.0','192.168.1.0','192.168.0.1','255.255.255.0','1.1.1.1','255.255.255.255','249.249.249.249','200.200.200.200','199.199.199.199','100.100.100.100','99.99.99.99','0.0.0.0','9.9.9.9','10.10.10.10','99.99.99.99','100.100.100.100','109.109.109.109','110.110.110.110','199.199.199.199','200.200.200.200','249.249.249.249','250.250.250.250','255.255.255.255','256.256.256.260','192.168.0.0/24','192.168..1','192.168.1','1','1.','1.1','1.1.','1.1.1','1.1.1.','1.1.1.1.','1.1.1.1.1','.1.1.1.1','01.01.01.01','09.09.09.09','1.0.0.1.0','010.1.1.1','123456','123123123123','.127.0.0.1'];
for (var i = 0; i < testAddr.length; i++) {
  document.getElementById('ipv4tests').innerHTML += '<li>' + testAddr[i] + ' ' + (isValidIpv4Addr(testAddr[i]) ? '<font color="green">VALID!</font>' : '<font color="red">INVALID!</font>') + '</li>';
}
<ul id="ipv4tests"></ul>

回答by kirill.buga

This works properly for all possible cases.

这适用于所有可能的情况。

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

回答by Ismael Miguel

I know this is old, but try this one:

我知道这是旧的,但试试这个:

    /^(?:(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)\.){3}(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)(?:\:(?:\d|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]))?$/

I made it today for a function in php.

我今天在 php 中做了一个函数。

It handles ip's from 0.0.0.0 to 255.255.255.255 and ports from 0 to 65535.

它处理从 0.0.0.0 到 255.255.255.255 的 ip 和从 0 到 65535 的端口。

Examples:

例子:

validates:
    0.0.0.0:0
    255.0.0.0
    192.168.1.0:8080
does not validate:
    192.168.0.0/24
    192.168..1
    192.168.1

I know this is a frankenregex, but still, it works!

我知道这是一个 frankenregex,但它仍然有效!

If port doesn't matter, use this one:

如果端口无关紧要,请使用这个:

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

回答by Slavik Meltser

Try this shortened one:

试试这个缩短的:

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

Here is the test case for this regex:

这是此正则表达式的测试用例:

  function verifyIp(ip)
  {
    return /^(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])(\.(?!$)|(?=$))){4}$/.test(ip||"");
  }
  
  ["192.68.35.35","0.0.0.0","255.0.0.0","192.168.1.0","192.168.0.1","255.255.255.0","1.1.1.1","255.255.255.255","249.249.249.249","200.200.200.200","199.199.199.199","100.100.100.100","99.99.99.99","0.0.0.0","9.9.9.9","10.10.10.10","99.99.99.99","100.100.100.100","109.109.109.109","110.110.110.110","199.199.199.199","200.200.200.200","249.249.249.249","250.250.250.250","255.255.255.255","256.256.256.260","192.168.0.0/24","192.168..1","192.168.1","1","1.","1.1","1.1.","1.1.1","1.1.1.","1.1.1.1.","1.1.1.1.1",".1.1.1.1","01.01.01.01","09.09.09.09","1.0.0.1.0","010.1.1.1","123456","123123123123",".127.0.0.1"].forEach(function(item){
    is_valid = verifyIp(item);
    $('<div>'+item+' <span class="'+(is_valid?'correct':'wrong')+'">'+(is_valid?'VALID':'INVALID')+'</span></div>').appendTo('#result');
  });
.item {
  font-weight: bold;
}
.wrong {
  color: red;  
}

.correct {
  color: green;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

回答by Prakash Thapa

Here is solution:

这是解决方案:

^(([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))\.){3}([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))$

回答by Raad Altaie

you can simply use this regex to validate any ip address without port number, like this format (192.168.1.1)

您可以简单地使用此正则表达式来验证没有端口号的任何 IP 地址,例如这种格式 (192.168.1.1)

/^(?:(?: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]?)$/

回答by David Faber

You might also try this:

你也可以试试这个:

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

We want the pattern to repeat exactly four times - in this case our pattern is a number in the range of 0 - 255 preceded by either a period .or the start of the string! Since the start of the string can occur only once, the other three occurrences must be periods.

我们希望模式正好重复四次——在这种情况下,我们的模式是一个 0 - 255 范围内的数字,前面是句点.或字符串的开头!由于字符串的开头只能出现一次,因此其他三个出现必须是句点。

Please see this Regex 101 demo for a full explanation.

请参阅此 Regex 101 演示以获取完整说明。

回答by Nick Grealy

Just extending on @DavidFaber 's excellent solution. To match an IPv4 "Dotted decimal" notation (no range/ports):

只是扩展@DavidFaber 的优秀解决方案。要匹配 IPv4“点分十进制”符号(无范围/端口):

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

Match examples:https://regex101.com/r/vX2hK4/15

匹配示例:https : //regex101.com/r/vX2hK4/15

Code golf anyone?

代码高尔夫有人吗?

回答by Rishul Matta

This reg ex works well but trust me its an overkill.
To have conditional comparisons like here less then 255its best to have combination of RegEx and conditionals.

这个 reg ex 效果很好,但相信我,它有点矫枉过正。
要进行像这里这样的条件比较小于255,最好结合 RegEx 和条件。

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