用于检查 IP 地址的 JavaScript 正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4460586/
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 12:30:40  来源:igfitidea点击:

javascript regular expression to check for IP addresses

javascriptregexstringstring-matching

提问by KennC.

I have several ip addresses like:

我有几个 IP 地址,例如:

  1. 115.42.150.37
  2. 115.42.150.38
  3. 115.42.150.50
  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)

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

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.

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

Thanks.

谢谢。

采纳答案by Spudley

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.

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

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.

希望有帮助。

回答by ErickBest

May be late but, someone could try:

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

Example of VALID IP address

有效 IP 地址示例

115.42.150.37
192.168.0.1
110.234.52.124

Example of INVALID IP address

无效 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]

JavaScript code to validate an IP address

用于验证 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)  
}  

回答by oriadam

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);});

回答by Andrew K

If you are using nodejs try:

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

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

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

doc net.isIP()

doc net.isIP()

回答by Teja Kantamneni

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"

回答by Ben McCormick

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

如果你想要一些比现代浏览器中 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;
}

回答by mikemaccana

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

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

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

isIp('192.168.0.1');

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

Will return a Boolean.

将返回一个布尔值。

Downvoters: care to explain why using an actively maintained library is better than copy pasting from a website?

Downvoters:注意解释为什么使用积极维护的库比从网站复制粘贴更好?

回答by Mahdi Pedram

Below Solution doesn't accept Padding Zeros

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

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

这是验证 IP 地址的最简洁方法,让我们分解一下:

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

事实:有效的 IP 地址是 has 4 octets,每个八位字节可以是介于0 - 255

Breakdown of Regex that matches any value between 0 - 255

匹配任何值之间的正则表达式的细分 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
  • 0matches 0
  • 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
  • 0火柴 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 RegExpyou should use \\.instead of \.since string will get escaped twice.

注意:使用时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}$`);
  return regex.test(str);
}

回答by Tom

/^(?!.*\.$)((?!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...

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

change:

改变

回答by SamWhan

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):

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

[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\dand finally 200-255: 2(5[0-5]|[0-4]\d).

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

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

这之前是对行首点的.测试,并且整个表达式由附加的{4}.测试 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.

在 regex101 上查看这里的一些示例。