如何验证IP地址...... [英] How to validate an IP address...

查看:135
本文介绍了如何验证IP地址......的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!我仍然在学习(TONS每天)并且有一个绝对的爆炸。不幸的是,我有一个令我困惑和困惑的问题。


看到最好的学习方法是重新发明轮子,我正在尝试编写一个脚本来验证IP地址(IPv4)是否有效。我只是在这的第一部分,我验证每个八位字节有1到3位数。嗯,这只是不起作用。


我尝试了以下3种不同的正则表达式:


1. m / \d {1,2} \.\\ \ {1,3} \. \ n {1,3} \.\d {1,3} /

2. m / \d\ n?\\ \?\\\\\\\\\\\\?\\\?\。\\\\\\\\\\
3. m / \d(\d\d?)?\。\\\(\\\?)?\。\\\(\\\ ?)?\。\\\(\\\?)?/


最后两个是直接从掌握正则表达式中获取的想法。书。它验证192.168.0.1是有效的,但所有3也验证1922.168.0.1也是有效的。我只是不明白为什么。


我在Windows XP上使用Active Perl 5.8.8,在Solaris 9上使用Perl 5.6.1。有关为什么这样做的任何帮助或指导如果工作不正常,我们将不胜感激。



更新:好的,我去完第一天的第一杯茶后,我又看了一眼正则表达式,并决定尝试在开始时使用^和VOILA !!成功!!现在,为什么它可以使用,但不是没有^,特别是当正则表达式从字符串的开头到结尾匹配时?此外,我测试了它们以及上述正则表达式的所有3个用于匹配IP格式的工作。



问候,


杰夫

解决方案

< blockquote>你可能应该使用^(字符串的开头)和


(字符串的结尾)来验证IP:


/ ^模式


/


否则您将验证部分匹配对于更广泛的模式将是真实的。

展开 | 选择 | Wrap | 行号


Hello everyone! I am still learning (TONS every day) and having an absolute blast. Unfortunately, I have an issue that is puzzling and bewildering me.

Seeing as how the best way to learn is to re-invent the wheel, I am trying to write a script to validate an IP address (IPv4) as valid. I am only in the first part of this, where I validate that each of the octets has 1 to 3 digits. Well, this just isn''t working.

I have tried the following 3 different regular expressions:

1. m/\d{1,2}\.\d{1,3}\.\d{1,3}\.\d{1,3}/
2. m/\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?/
3. m/\d(\d\d?)?\.\d(\d\d?)?\.\d(\d\d?)?\.\d(\d\d?)?/

The last two were ideas taken directly from the "Mastering Regular Expressions" book. It validates that 192.168.0.1 is valid, but all 3 also validate the 1922.168.0.1 is valid as well. I just don''t understand why.

I am using Active Perl 5.8.8 on Windows XP and also Perl 5.6.1 on Solaris 9. Any help or guidance as to WHY this is not working correctly would be greatly appreciated.


UPDATE: Ok, after I went and finished my first cup of tea of the day, I took a look again at my regex and decided to try putting a ^ at the beginning and VOILA!! Success!! Now, why does it work with, but not without the ^, especially when the regex is matching from beginning to end of the string? Also, I tested them and all 3 of the above regex''s work for matching the format of an IP.



Regards,

Jeff

解决方案

You probably should be using ^ (beginning of string) and


(end of string) to validate the IP:

/^pattern


/

otherwise you are validating partial matches will will be true for a wider range of patterns.

Expand|Select|Wrap|Line Numbers


这篇关于如何验证IP地址......的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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