in reply to Validate Ip address Regexp
Your regex would validate an address such as 258.344.543.877, whereas none of the digit groups fits the definition of an IP address, as they are all larger than 255.
How do we check that the numbers are correct?
One possible way is to start by creating an $octet regex, which will match only numbers between 0 and 255. It could be something like this:
which basically means: 1 or 2 digits (0-99), OR a 0 or 1 followed by 2 digits (000-199), OR a 2 followed by a digit between 0 and 4 and any other digit (200-249), OR a 25 followed by a digit between 0 and 5 (250-255).my $octet = qr/\d{1,2}|[01]\d{2}|2[0-4]\d|25[0-5]/;
Once you have defined such an $octet regex, you can use it to further define an $ip regex:
in which you may want to factor out the repetition of $octet with something like this:my $ip = qr/^$octet\.$octet\.$octet\.$octet$/;
which is, at best, only marginally clearer.my $ip = qr/^(?:$octet\.){3}$octet$/;
Provided I did not make any small silly mistake in the code above (I only tested a few obvious cases), this should really be able to validate any valid IPv4 address (and hopefully reject any invalid one).
Please note that I am providing the above only because you stated that you wanted to try on your own, and also because learning to build a regex from a sub-regex is sometimes really useful and may give you an initial idea of what Perl 6's or other regex-based grammars are about.
For a real life Perl 5 application, I would agree with other monks above, really recommend not to try to reinvent the wheel and advise you to use the proper ready-made module (such as Regexp::Common::net), which has undoubtedly been more thoroughly tested than my quick attempt above.
|
|---|