使用正则表达式验证IPv4地址 [英] Validating IPv4 addresses with regexp

查看:668
本文介绍了使用正则表达式验证IPv4地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试为IPv4验证获得高效的正则表达式,但没有多少运气。看起来有一点我用(25 [0-5] | 2 [0-4] [0-9] | [01]?[0-9] [0-9] ?(\。| $)){4} ,但会产生一些奇怪的结果:

I've been trying to get an efficient regex for IPv4 validation, but without much luck. It seemed at one point I had had it with (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(\.|$)){4}, but it produces some strange results:

[chris@helios bashscripts]$ grep --version
grep (GNU grep) 2.7


[chris@helios bashscripts]$ 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
[chris@helios bashscripts]$ 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
[chris@helios bashscripts]$ grep -E '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(\.|$)){4}\b' <<< 192.168.255.255
[chris@helios bashscripts]$ 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数字,或不适合我。

I did a search to see if this had already been asked and answered, but other answers appear to simply show how to determine 4 groups of 1-3 numbers, or do not work for me.

任何想法?谢谢!

推荐答案

你已经有了一个可行的答案,但万一你很好奇你的原始方法有什么问题,答案是你需要围绕交替使用小括号,否则只有小于200时才需要(\。| $)

You've already got a working answer but just in case you are curious what was wrong with your original approach, the answer is that you need parentheses around your alternation otherwise the (\.|$) is only required if the number is less than 200.

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

这篇关于使用正则表达式验证IPv4地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆