使用regexp验证IPv4地址

时间:2011-03-12 17:27:25

标签: regex validation ip-address ipv4 grep

我一直在努力为IPv4验证获得高效的正则表达式,但没有太多运气。似乎有一点我用(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(\.|$)){4}得到了它,但它产生了一些奇怪的结果:

$ grep --version
grep (GNU grep) 2.7
$ grep -E '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(\.|$)){4}\b' <<< 192.168.1.1
192.168.1.1
$ grep -E '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(\.|$)){4}\b' <<< 192.168.1.255
192.168.1.255
$ grep -E '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(\.|$)){4}\b' <<< 192.168.255.255
$ grep -E '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(\.|$)){4}\b' <<< 192.168.1.2555
192.168.1.2555

我做了一个搜索,看看是否已经被问过并回答了,但其他答案似乎只是显示如何确定4组1-3个数字,或者不适合我。

41 个答案:

答案 0 :(得分:68)

你已经得到了一个有效的答案,但万一你好奇你原来的方法有什么问题,答案是你需要围绕你的交替使用括号,否则(\.|$)仅在数字为不到200。

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

答案 1 :(得分:48)

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

接受

127.0.0.1
192.168.1.1
192.168.1.255
255.255.255.255
0.0.0.0
1.1.1.01

<强>拒绝

30.168.1.255.1
127.1
192.168.1.256
-1.2.3.4
3...3

使用单元测试在线尝试:https://www.debuggex.com/r/-EDZOqxTxhiTncN6/1

答案 2 :(得分:26)

正则表达式不是这项工作的工具。编写一个分隔四个数字的解析器并检查它们是否在[0,255]范围内会更好。非功能正则表达式已经不可读了!

答案 3 :(得分:11)

新的和改进的短版

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

它使用否定前瞻(?!)来删除ip可能以.

结尾的情况

旧答案

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

我认为这是最准确和最严格的正则表达式,它不接受像000.021.01.0.之类的东西,它似乎像其他大多数答案一样,需要额外的正则表达式来拒绝类似于那个的情况 - 即{{1起始数字和以0

结尾的IP

答案 4 :(得分:9)

IPv4地址(准确捕获) 匹配0.0.0.0到255.255.255.255 使用此正则表达式将IP编号与accurracy匹配。 4个数字中的每一个都存储在一个捕获组中,因此您可以访问它们以进行进一步处理。

\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

取自JGsoft RegexBuddy图书馆

编辑:此(\.|$)部分似乎很奇怪

答案 5 :(得分:5)

我正在寻找类似于IPv4地址的东西 - 一个正则表达式,它也阻止了常用的私有IP地址被验证(192.168.xy,10.xyz,172.16.xy)所以使用负面预测来完成这个:< / p>

(?!(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.).*)
(?!255\.255\.255\.255)(25[0-5]|2[0-4]\d|[1]\d\d|[1-9]\d|[1-9])
(\.(25[0-5]|2[0-4]\d|[1]\d\d|[1-9]\d|\d)){3}

(当然,这些应该在一行上,为了便于阅读而在3个单独的行上格式化) Regular expression visualization

Debuggex Demo

它可能没有针对速度进行优化,但只在寻找“真实”的时候效果很好。互联网地址。

将会(并且应该)失败的事情:

0.1.2.3         (0.0.0.0/8 is reserved for some broadcasts)
10.1.2.3        (10.0.0.0/8 is considered private)
172.16.1.2      (172.16.0.0/12 is considered private)
172.31.1.2      (same as previous, but near the end of that range)
192.168.1.2     (192.168.0.0/16 is considered private)
255.255.255.255 (reserved broadcast is not an IP)
.2.3.4
1.2.3.
1.2.3.256
1.2.256.4
1.256.3.4
256.2.3.4
1.2.3.4.5
1..3.4

将(并且应该)工作的IP:

1.0.1.0         (China)
8.8.8.8         (Google DNS in USA)
100.1.2.3       (USA)
172.15.1.2      (USA)
172.32.1.2      (USA)
192.167.1.2     (Italy)

如果其他人正在寻找验证的互联网IP地址不包括公共私人地址&#39;

答案 6 :(得分:3)

我认为阅读这篇文章的许多人都在寻找更简单的正则表达式,即使它们与某些技术上无效的IP地址匹配也是如此。 (而且,正如其他地方所指出的那样,正则表达式可能不是正确验证IP地址的正确工具。)

如果您不想匹配行的开头/结尾,请删除^,并在适用时将$替换为\b

基本正则表达式(BRE)(已在GNU grep,GNU sed和vim上测试):

/^[0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+$/

扩展正则表达式(ERE):

/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/

或:

/^([0-9]+(\.|$)){4}/

与Perl兼容的正则表达式(PCRE)(在Perl 5.18上进行了测试):

/^\d+\.\d+\.\d+\.\d+$/

或:

/^(\d+(\.|$)){4}/

Ruby(在Ruby 2.1上进行了测试):

尽管应该是PCRE,但Ruby出于某种原因允许Perl 5.18不允许使用此正则表达式:

/^(\d+[\.$]){4}/

我对所有这些的测试都在线here

答案 7 :(得分:3)

这比一些更长,但这是我用来匹配IPv4地址的。简单而不妥协。

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

答案 8 :(得分:2)

对于0到255之间的数字,我使用此正则表达式:

(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))

以上正则表达式将匹配0到255之间的整数,但不匹配256。

因此对于IPv4,我使用此正则表达式:

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

它的结构如下:^(N)((\.(N)){3})$,其中N是用于匹配0到255之间的数字的正则表达式。
该正则表达式将与IP匹配,如下所示:

0.0.0.0
192.168.1.2

但不包含以下内容:

10.1.0.256
1.2.3.
127.0.1-2.3

对于IPv4 CIDR(无类域间路由),我使用此正则表达式:

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

结构如下:^(N)((\.(N)){3})\/M$,其中N是用于匹配0到255之间的数字的正则表达式,而M是用于匹配0到32之间的数字的正则表达式。
此正则表达式将与CIDR匹配,如下所示:

0.0.0.0/0
192.168.1.2/32

但不包含以下内容:

10.1.0.256/16
1.2.3./24
127.0.0.1/33

对于"10.0.0.0/16", "192.168.1.1/32"这样的IPv4 CIDR列表,我使用以下正则表达式:

^("(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})\/(([0-9])|([12][0-9])|(3[0-2]))")((,([ ]*)("(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})\/(([0-9])|([12][0-9])|(3[0-2]))"))*)$

它的结构如下:^(“C”)((,([ ]*)(“C”))*)$,其中C是用于匹配CIDR的正则表达式(例如0.0.0.0/0)。
此正则表达式将与CIDR列表匹配,如下所示:

“10.0.0.0/16”,”192.168.1.2/32”, “1.2.3.4/32”

但不包含以下内容:

“10.0.0.0/16” 192.168.1.2/32 “1.2.3.4/32”

也许它会变短,但是对我来说,我很容易理解它。

希望有帮助!

答案 9 :(得分:1)

这是一个更好的,附有通过/失败的 IP

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

接受

127.0.0.1
192.168.1.1
192.168.1.255
255.255.255.255
10.1.1.1
0.0.0.0

拒绝

1.1.1.01
30.168.1.255.1
127.1
192.168.1.256
-1.2.3.4
1.1.1.1.
3...3
192.168.1.099

答案 10 :(得分:1)

我试图使其更简单,更短。

  

1.26.0

如果您正在寻找java / kotlin:

  

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

如果有人想知道它的工作原理,请进行以下说明。真的很简单。只需尝试一下:p:

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

从数学上讲,它就像:

 1. ^.....$: '^' is the starting and '$' is the ending.

 2. (): These are called a group. You can think of like "if" condition groups.

 3. |: 'Or' condition - as same as most of the programming languages.

 4. [01]?\d{1,2}: '[01]' indicates one of the number between 0 and 1. '?' means '[01]' is optional. '\d' is for any digit between 0-9 and '{1,2}' indicates the length can be between 1 and 2. So here the number can be 0-199.

 5. 2[0-4]\d: '2' is just plain 2. '[0-4]' means a number between 0 to 4. '\d' is for any digit between 0-9. So here the number can be 200-249.

 6. 25[0-5]: '25' is just plain 25. '[0-5]' means a number between 0 to 5. So here the number can be 250-255.

 7. \.: It's just plan '.'(dot) for separating the numbers.

 8. {3}: It means the exact 3 repetition of the previous group inside '()'.

 9. ([01]?\d{1,2}|2[0-4]\d|25[0-5]): Totally same as point 2-6

因此,如您通常所见,这就是IP地址的模式。希望对理解正则表达式有所帮助。 :p

答案 11 :(得分:1)

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

答案 12 :(得分:1)

''' 这段代码对我有用,就这么简单。

在这里,我已经采用了ip的值,并且试图将其与正则表达式匹配。

ip="25.255.45.67"    

op=re.match('(\d+).(\d+).(\d+).(\d+)',ip)

if ((int(op.group(1))<=255) and (int(op.group(2))<=255) and int(op.group(3))<=255) and (int(op.group(4))<=255)):

print("valid ip")

else:

print("Not valid")

以上条件检查所有4个八位位组的值是否都超过255,则该值无效。但是在应用条件之前,由于值在字符串中,因此必须将它们转换为整数。

group(0)打印匹配的输出,而group(1)打印第一个匹配的值,此处为“ 25”,依此类推。 '''

答案 13 :(得分:1)

以上答案是有效的,但是如果ip地址不在行尾并且在文本之间,该怎么办。此正则表达式甚至可以解决该问题。

代码:'\b((([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]))\b'

输入文本文件:

ip address 0.0.0.0 asfasf
 sad sa 255.255.255.255 cvjnzx
zxckjzbxk  999.999.999.999 jshbczxcbx
sjaasbfj 192.168.0.1 asdkjaksb
oyo 123241.24121.1234.3423 yo
yo 0000.0000.0000.0000 y
aw1a.21asd2.21ad.21d2
yo 254.254.254.254 y0
172.24.1.210 asfjas
200.200.200.200
000.000.000.000
007.08.09.210
010.10.30.110

输出文字:

0.0.0.0
255.255.255.255
192.168.0.1
254.254.254.254
172.24.1.210
200.200.200.200

答案 14 :(得分:1)

(((25[0-5])|(2[0-4]\d)|(1\d{2})|(\d{1,2}))\.){3}(((25[0-5])|(2[0-4]\d)|(1\d{2})|(\d{1,2})))

测试以查找文本中的匹配项, https://regex101.com/r/9CcMEN/2

以下是在每个IP地址编号中定义有效组合的规则:

  • 任何一位或两位数字。
  • 1开头的任意三位数字。

  • 如果第二个数字为2,则以0开头的任意三位数字 通过4

  • 如果第三个数字为25,则以0开头的任意三位数字 通过5

让我们用(((25[0-5])|(2[0-4]\d)|(1\d{2})|(\d{1,2}))\.)开始,一组四个嵌套的子表达式,我们将以相反的顺序查看它们。 (\d{1,2})匹配任何一位或两位数字099(1\d{2})匹配以11后跟任意两位数)开头的任意三位数字,或者数字100199(2[0-4]\d)将数字200249匹配。 (25[0-5])将数字250255匹配。这些子表达式中的每一个都包含在另一个子表达式中,每个子表达式之间都有|(因此四个子表达式中的一个必须匹配,而不是全部)。在数字范围\.匹配.之后,整个系列(所有数字选项加\.)被包含在另一个子表达式中,并使用{{1}重复三次}}。最后,重复数字范围(此时没有尾随{3})以匹配最终的IP地址编号。通过将四个数字中的每一个限制为\.0之间的值,此模式确实可以匹配有效的IP地址并拒绝无效的地址。

  

摘自:Ben Forta. “Learning Regular Expressions.”

如果在IP地址的开头和结尾都不需要字符,则应分别使用255^元字符。

$

测试以查找文本中的匹配项, https://regex101.com/r/uAP31A/1

答案 15 :(得分:1)

使用子网掩码:

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

答案 16 :(得分:1)

我设法从所有其他答案构建一个正则表达式。

(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]?)){3}

答案 17 :(得分:0)

以下是用于验证IP地址的正则表达式。

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

答案 18 :(得分:0)

我的[扩展]方法→用于以空格分隔的IP地址的正则表达式:

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

使用PCRE前瞻。

答案 19 :(得分:0)

Java IPV4地址的有效正则表达式

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

答案 20 :(得分:0)

我试图使其更简单,更短。

  

^(([[01]?\ d {1,2} | 2 [0-4] \ d | 25 [0-5])。){3}([01]?\ d {1,2 } | 2 [0-4] \ d | 25 [0-5])$

如果您正在寻找java / kotlin:

  

^(([[01]?\ d {1,2} | 2 [0-4] \ d | 25 [0-5])\。){3}([01]?\ d {1, 2} | 2 [0-4] \ d | 25 [0-5])$

如果有人想知道它的工作原理,请进行以下说明。真的很简单。只需尝试一下:p:

 1. ^.....$: '^' is the starting and '$' is the ending.

 2. (): These are called a group. You can think of like "if" condition groups.

 3. |: 'Or' condition - as same as most of the programming languages.

 4. [01]?\d{1,2}: '[01]' indicates one of the number between 0 and 1. '?' means '[01]' is optional. '\d' is for any digit between 0-9 and '{1,2}' indicates the length can be between 1 and 2. So here the number can be 0-199.

 5. 2[0-4]\d: '2' is just plain 2. '[0-4]' means a number between 0 to 4. '\d' is for any digit between 0-9. So here the number can be 200-249.

 6. 25[0-5]: '25' is just plain 25. '[0-5]' means a number between 0 to 5. So here the number can be 250-255.

 7. \.: It's just plan '.'(dot) for separating the numbers.

 8. {3}: It means the exact 3 repetition of the previous group inside '()'.

 9. ([01]?\d{1,2}|2[0-4]\d|25[0-5]): Totally same as point 2-6

从数学上讲,它就像:

(0-199 OR 200-249 OR 250-255).{Repeat exactly 3 times}(0-199 OR 200-249 OR 250-255)

因此,如您通常所见,这就是IP地址的模式。希望对理解正则表达式有所帮助。 :p

答案 21 :(得分:0)

    const char*ipv4_regexp = "\\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";

我将JGsoft RegexBuddy库中的正则表达式改编为C语言(regcomp / regexec),我发现它有效,但在Linux等操作系统中存在一些问题。 该正则表达式接受ipv4地址,如192.168.100.009,其中Linux中的009被视为八进制值,因此地址不是您想到的地址。 我改变了正则表达式如下:

    const char* ipv4_regex = "\\b(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])\\b";

使用那个正则表达式现在192.168.100.009不是有效的ipv4地址,而192.168.100.9是可以​​的。

我也修改了多播地址的正则表达式,它是以下内容:

    const char* mcast_ipv4_regex = "\\b(22[4-9]|23[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])\\b";

我认为你必须使正则表达式适应你用来开发应用程序的语言

我在java中添加了一个例子:

    package utility;

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    public class NetworkUtility {

        private static String ipv4RegExp = "\\b(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d?)\\b";

        private static String ipv4MulticastRegExp = "2(?:2[4-9]|3\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d?|0)){3}";

        public NetworkUtility() {

        }

        public static boolean isIpv4Address(String address) {
            Pattern pattern = Pattern.compile(ipv4RegExp);
            Matcher matcher = pattern.matcher(address);

            return matcher.matches();
        }

        public static boolean isIpv4MulticastAddress(String address) {
             Pattern pattern = Pattern.compile(ipv4MulticastRegExp);
             Matcher matcher = pattern.matcher(address);

             return matcher.matches();
        }
    }

答案 22 :(得分:0)

我在此页面中看到非常糟糕的正则表达式。.所以我附带了自己的:

\b((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\b

说明:

num-group = (0-9|10-99|100-199|200-249|250-255)
<border> + { <num-group> + <dot-cahracter> }x3 + <num-group> + <border>

您可以在这里验证其工作原理here

答案 23 :(得分:0)

-bash-3.2$ echo "191.191.191.39" | egrep 
  '(^|[^0-9])((2([6-9]|5[0-5]?|[0-4][0-9]?)?|1([0-9][0-9]?)?|[3-9][0-9]?|0)\.{3}
     (2([6-9]|5[0-5]?|[0-4][0-9]?)?|1([0-9][0-9]?)?|[3-9][0-9]?|0)($|[^0-9])'

>> 191.191.191.39

(这是一个与整个地址空间(包括广播等)相匹配的DFA。

答案 24 :(得分:0)

该IP地址仅匹配有效的IP(不带前缀0,但无论其“功能”如何(例如,保留,私有等),它都将匹配0-255之间的八位字节),并允许进行内联匹配,其中可能在空格之前和/或在IP之后,或使用CIDR表示法时。

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

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '10.0.1.2'
10.0.1.2

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address 10.0.1.2'
ip address 10.0.1.2

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address 10.0.1.2 255.255.255.255'
ip address 10.0.1.2 255.255.255.255

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address 10.0.1.2/32'
ip address 10.0.1.2/32

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address 10.0.1.2.32'
$

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address10.0.1.2'
$

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '10.0.1.256'
$

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '0.0.0.0'
0.0.0.0

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '255.255.255.255'
255.255.255.255

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '255.255.255.256'
$

当然,在IP内联的情况下,如果您只想要整个IP,而只需要IP,则可以使用grep选项“ -o”和您喜欢的空白微调。

对于我们使用python的人来说,等效的大致是:

>>> ipv4_regex = re.compile(r'(^| )((?:[1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(?:[1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])($| |/)')
>>> ipv4_regex.search('ip address 10.1.2.3/32')
<re.Match object; span=(10, 20), match=' 10.1.2.3/'>

如果您像我这样挑剔(懒惰),您可能更愿意使用分组来获取整个IP,而仅获得IP或CIDR,仅获得CIDR或它们的某种组合。我们可以使用(?P) syntax来命名我们的组,以便于参考。

>>> ipv4_regex = re.compile(r'(?:^| )(?P<address>((?:[1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(?:[1-9]?\d|1\d{2}|2[0-4]\d|25[0-5]))(?P<slash>/)?(?(slash)(?P<cidr>[0-9]|[12][0-9]|3[0-2]))(?:$| )')
>>> match = ipv4_regex.search('ip address 10.0.1.2/32')
>>> match.group('address')
'10.0.1.2'
>>> match.group('cidr')
'32'
>>> "".join((match.group('address'), match.group('slash'), match.group('cidr')))
'10.0.1.2/32'

当然,有不只使用正则表达式的方法。您可以检查以下一些条件(该条件找不到内联,只是验证传递的地址是否有效)。

首先检查地址中的每个字符是一个数字还是一个'。'

接下来检查是否恰好有3个'。'

接下来的两个检查将检查每个八位位组是否在0到255之间。

最后检查是没有八位位组前面加一个'0'

def validate_ipv4_address(address):
    return all(re.match('\.|\d', c) for c in address) \
        and address.count('.') == 3 \
        and all(0 <= int(octet) <= 255 for octet in address.split('.')) \
        and all((len(bin(int(octet))) <= 10 for octet in address.split('.'))) \
        and all(len(octet) == 1 or d[0] != '0' for octet in address.split('.'))


>>> validate_ipv4_address('255.255.255.255')
True
>>> validate_ipv4_address('10.0.0.1')
True
>>> validate_ipv4_address('01.01.01.01')
False
>>> validate_ipv4_address('123.456.789.0')
False
>>> validate_ipv4_address('0.0.0.0')
True
>>> validate_ipv4_address('-1.0.0.0')
False
>>> validate_ipv4_address('1.1.1.')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in validate_ipv4_address
  File "<stdin>", line 4, in <genexpr>
ValueError: invalid literal for int() with base 10: ''
>>> validate_ipv4_address('.1.1.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in validate_ipv4_address
  File "<stdin>", line 4, in <genexpr>
ValueError: invalid literal for int() with base 10: ''
>>> validate_ipv4_address('1..1.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in validate_ipv4_address
  File "<stdin>", line 4, in <genexpr>
ValueError: invalid literal for int() with base 10: ''

(按位,每个八位位组应为8位或更少,但每个前缀前面都应带有'0b')

>>> bin(0)
'0b0'
>>> len(bin(0))
3
>>> bin(255)
'0b11111111'
>>> len(bin(256))
11

答案 25 :(得分:0)

我认为这是最短的。

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

答案 26 :(得分:0)

简便方法

((25[0-5]|2[0-4][0-9]|[1][0-9][0-9]|[1-9][0-9]{0,1})\.){3}(25[0-5]|2[0-4][0-9]|[1][0-9][0-9]|[1-9][0-9]{0,1})

Demo

答案 27 :(得分:0)

试试这个

<块引用>

^(127|10).[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}"

答案 28 :(得分:0)

year=1900

答案 29 :(得分:0)

尝试一下:

\b(([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-5][0-5])\.([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-5][0-5])\.([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-5][0-5])\.(2[0-5][0-5]|1[0-9][0-9]|[1-9][0-9]|[1-9]))\b

答案 30 :(得分:0)

此模式不包括 52 个符号并接受以零开头的 cuncks。

import React, { useEffect, useState } from "react";
import { useStoreState, useStoreActions } from "./hooks";
export default function App() {
  const localStorageLayouts = useStoreState(
    (state) => state.appData.localStorageLayouts
  );
    const [availableLayouts, setAvailableLayouts] = useState(localStorageLayouts);
    useEffect(() => {
      setAvailableLayouts(localStorageLayouts);
    }, [localStorageLayouts]);

    return (
        //...
        <div>
        <VeryExpensiveToRender/>
        <ShouldUpdate layouts = {availableLayouts}/>
        <OkNotToUpdate/>
        <ShouldUpdate layouts = {availableLayouts}/>
        <OkNotToUpdate/>
        </div>
    )
}

答案 31 :(得分:0)

我能想象的最精确,最简单,最紧凑的IPv4 regexp是

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

但是......的性能/效率怎么样?对不起我不知道,谁在乎呢?

答案 32 :(得分:0)

我会使用PCRE和define关键字:

/^
 ((?&byte))\.((?&byte))\.((?&byte))\.((?&byte))$
 (?(DEFINE)
     (?<byte>25[0-5]|2[0-4]\d|[01]?\d\d?))
/gmx

演示:https://regex101.com/r/IB7j48/2

这样做的原因是避免重复(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)模式四次。其他解决方案(例如下面的解决方案)运行良好,但它并不像许多人所要求的那样捕获每个组。

/^((\d+?)(\.|$)){4}/ 

拥有4个捕获组的唯一方法是重复该模式四次:

/^(?<one>\d+)\.(?<two>\d+)\.(?<three>\d+)\.(?<four>\d+)$/

因此非常容易在perl中捕获ipv4

$ echo "Hey this is my IP address 138.131.254.8, bye!" | \
  perl -ne 'print "[$1, $2, $3, $4]" if \
    /\b((?&byte))\.((?&byte))\.((?&byte))\.((?&byte))
     (?(DEFINE)
        \b(?<byte>25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))
    /x'

[138, 131, 254, 8]

答案 33 :(得分:0)

我发现这个示例非常有用,而且它允许使用不同的ipv4表示法。

使用python的示例代码:

    def is_valid_ipv4(ip4):
    """Validates IPv4 addresses.
    """
    import re
    pattern = re.compile(r"""
        ^
        (?:
          # Dotted variants:
          (?:
            # Decimal 1-255 (no leading 0's)
            [3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}
          |
            0x0*[0-9a-f]{1,2}  # Hexadecimal 0x0 - 0xFF (possible leading 0's)
          |
            0+[1-3]?[0-7]{0,2} # Octal 0 - 0377 (possible leading 0's)
          )
          (?:                  # Repeat 0-3 times, separated by a dot
            \.
            (?:
              [3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}
            |
              0x0*[0-9a-f]{1,2}
            |
              0+[1-3]?[0-7]{0,2}
            )
          ){0,3}
        |
          0x0*[0-9a-f]{1,8}    # Hexadecimal notation, 0x0 - 0xffffffff
        |
          0+[0-3]?[0-7]{0,10}  # Octal notation, 0 - 037777777777
        |
          # Decimal notation, 1-4294967295:
          429496729[0-5]|42949672[0-8]\d|4294967[01]\d\d|429496[0-6]\d{3}|
          42949[0-5]\d{4}|4294[0-8]\d{5}|429[0-3]\d{6}|42[0-8]\d{7}|
          4[01]\d{8}|[1-3]\d{0,9}|[4-9]\d{0,8}
        )
        $
    """, re.VERBOSE | re.IGNORECASE)
    return pattern.match(ip4) <> None

答案 34 :(得分:0)

  

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

以上将是ip地址的正则表达式,如: 221.234.000.112 也适用于221.234.0.112,221.24.03.112,221.234.0.1

你可以想象上面所有类型的地址

答案 35 :(得分:0)

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

这个正则表达式不会接受 08.8.8.8或8.08.8.8或8.8.08.8或8.8.8.08

答案 36 :(得分:0)

只要IP包裹在除数字之外的任何字符(IP后面或前面),就会找到有效的IP地址。已创建4个反向引用:$ + {first}。$ + {second}。$ + {third}。$ + {forth}

Find String:
#any valid IP address
(?<IP>(?<![\d])(?<first>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<second>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<third>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<forth>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))(?![\d]))
#only valid private IP address RFC1918
(?<IP>(?<![\d])(:?(:?(?<first>10)[\.](?<second>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5])))|(:?(?<first>172)[\.](?<second>(:?1[6-9])|(:?2[0-9])|(:?3[0-1])))|(:?(?<first>192)[\.](?<second>168)))[\.](?<third>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<forth>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))(?![\d]))

Notepad++ Replace String Option 1: Replaces the whole IP (NO Change):
$+{IP}

Notepad++ Replace String Option 2: Replaces the whole IP octect by octect (NO Change)
$+{first}.$+{second}.$+{third}.$+{forth}

Notepad++ Replace String Option 3: Replaces the whole IP octect by octect (replace 3rd octect value with 0)
$+{first}.$+{second}.0.$+{forth}
NOTE: The above will match any valid IP including 255.255.255.255 for example and change it to 255.255.0.255 which is wrong and not very useful of course.

用实际值替换每个octect的部分,但是你可以构建自己的find和replace,这对于修改文本文件中的IP是非常有用的:

for example replace the first octect group of the original Find regex above:
(?<first>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))
with
(?<first>10)

and
(?<second>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))
with
(?<second>216)
and you are now matching addresses starting with first octect 192 only

Find on notepad++:
(?<IP>(?<![\d])(?<first>10)[\.](?<second>216)[\.](?<third>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<forth>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))(?![\d]))

你仍然可以使用反向引用组以与以前完全相同的方式执行替换。

您可以了解以上内容如何匹配:

cat ipv4_validation_test.txt
Full Match:
0.0.0.1
12.108.1.34
192.168.1.1
10.249.24.212
10.216.1.212
192.168.1.255
255.255.255.255
0.0.0.0


Partial Match (IP Extraction from line)
30.168.1.0.1
-1.2.3.4
sfds10.216.24.23kgfd
da11.15.112.255adfdsfds
sfds10.216.24.23kgfd


NO Match
1.1.1.01
3...3
127.1.
192.168.1..
192.168.1.256
da11.15.112.2554adfdsfds
da311.15.112.255adfdsfds

使用grep,您可以看到以下结果:

From grep:
grep -oP '(?<IP>(?<![\d])(?<first>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<second>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<third>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<forth>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))(?![\d]))' ipv4_validation_test.txt
0.0.0.1
12.108.1.34
192.168.1.1
10.249.24.212
10.216.1.212
192.168.1.255
255.255.255.255
0.0.0.0
30.168.1.0
1.2.3.4
10.216.24.23
11.15.112.255
10.216.24.23


grep -P '(?<IP>(?<![\d])(?<first>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<second>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<third>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<forth>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))(?![\d]))' ipv4_validation_test.txt
0.0.0.1
12.108.1.34
192.168.1.1
10.249.24.212
10.216.1.212
192.168.1.255
255.255.255.255
0.0.0.0
30.168.1.0.1
-1.2.3.4
sfds10.216.24.23kgfd
da11.15.112.255adfdsfds
sfds10.216.24.23kgfd


#matching ip addresses starting with 10.216
grep -oP '(?<IP>(?<![\d])(?<first>10)[\.](?<second>216)[\.](?<third>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<forth>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))(?![\d]))' ipv4_validation_test.txt
10.216.1.212
10.216.24.23
10.216.24.23

答案 37 :(得分:-1)

IPv4地址是一件非常复杂的事情。

注意:缩进和衬里仅用于说明目的,在真实的RegEx中不存在。

\b(
  ((
    (2(5[0-5]|[0-4][0-9])|1[0-9]{2}|[1-9]?[0-9])
  |
    0[Xx]0*[0-9A-Fa-f]{1,2}
  |
    0+[1-3]?[0-9]{1,2}
  )\.){1,3}
  (
    (2(5[0-5]|[0-4][0-9])|1[0-9]{2}|[1-9]?[0-9])
  |
    0[Xx]0*[0-9A-Fa-f]{1,2}
  |
    0+[1-3]?[0-9]{1,2}
  )
|
  (
    [1-3][0-9]{1,9}
  |
    [1-9][0-9]{,8}
  |
    (4([0-1][0-9]{8}
      |2([0-8][0-9]{7}
        |9([0-3][0-9]{6}
          |4([0-8][0-9]{5}
            |9([0-5][0-9]{4}
              |6([0-6][0-9]{3}
                |7([0-1][0-9]{2}
                  |2([0-8][0-9]{1}
                    |9([0-5]
    ))))))))))
  )
|
  0[Xx]0*[0-9A-Fa-f]{1,8}
|
  0+[1-3]?[0-7]{,10}
)\b

这些IPv4地址由上述RegEx验证。

127.0.0.1
2130706433
0x7F000001
017700000001
0x7F.0.0.01 # Mixed hex/dec/oct
000000000017700000001 # Have as many leading zeros as you want
0x0000000000007F000001 # Same as above
127.1
127.0.1

这些都被拒绝了。

256.0.0.1
192.168.1.099 # 099 is not a valid number
4294967296 # UINT32_MAX + 1
0x100000000
020000000000

答案 38 :(得分:-1)

这是正则表达式对我有用:
"\<((([1-9]|1[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([1-9]|1[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))\>"

答案 39 :(得分:-3)

String zeroTo255 = "([0-9]|[0-9][0-9]|(0|1)[0-9][0-9]|2[0-4][0-9]|25[0-5])";

it can contain single digit i.e ([0-9]);  
It can contain two digits i.e ([0-9][0-9]); 
range is (099 to 199)i.e((0|1)[0-9][0-9]); 
range is (200 - 249) i.e (2[0-9][0-9]) ; 
range is (250-255) i.e(25[0-5]);

答案 40 :(得分:-3)

mysql> select ip from foo where ip regexp '^\\s*[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]\\s*';