正则表达式检查 IP 是否有效 [英] Regexp to check if an IP is valid

查看:61
本文介绍了正则表达式检查 IP 是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以将正则表达式中的值与 Python 中的正则表达式系统进行比较.匹配 IP 的模式很容易,但每个 1-3 位数字都不能超过 255,这让我有点困惑.

I'm wondering if it's possible to compare values in regexps with the regexp system in Python. Matching the pattern of an IP is easy, but each 1-3 digits cannot be above 255 and that's where I'm a bit stumped.

推荐答案

您需要检查每个位置允许的数字.对于第一个可选数字,可接受的值为 0-2.对于第二个,0-5(如果该部分的第一个数字存在,否则为 0-9),第三个为 0-9.

You need to check the allowed numbers in each position. For the first optional digit, acceptable values are 0-2. For the second, 0-5 (if the first digit for that part is present, otherwise 0-9), and 0-9 for the third.

我在 http://www.regular-expressions.info/找到了这个带注释的示例regexbuddy/ipaccurate.html :

\b(?:(?: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]?)\b

这篇关于正则表达式检查 IP 是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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