|
|
 |
|
Title: Match an IP address
Submitter: Ken Simpson
(other recipes)
Last Updated: 2003/10/23
Version no: 1.0
Category:
Networking
|
|
5 vote(s)
|
|
|
|
Description:
This regex matches IP addresses in the dotted quad form. It comes courtesy of Jeffrey Friedl's "Mastering Regular Expressions".
Usage: Text Source
my $ReIpNum = qr{([01]?\d\d?|2[0-4]\d|25[0-5])};
my $ReIpAddr = qr{^$ReIpNum\.$ReIpNum\.$ReIpNum\.$ReIpNum$};
my %ips = ('0.0.0.0' => 1,
'1.2.3.4' => 1,
'255.255.255.255' => 1,
'000.34.2000.2' => 0,
'' => 0,
'24.23.23.' => 0);
for my $ip(keys %ips) {
die "Failed: $ip"
unless (($ip =~ m{$ReIpAddr}) == $ips{$ip});
print "$ip passed\n";
}
The license for this recipe is available here.
Discussion:
|
|
Add comment
|
|
Number of comments: 6
IP address matching, Nigel Horne, 2005/02/09
I believe that is more than a regular expression, it also includes perl code.
What about this RE?
^(([3-9]\d?|[01]\d{0,2}|2\d?|2[0-4]\d|25[0-5])\.){3}([3-9]\d?|[01]\d{0,2}|2\d?|2[0-4]\d|25[0-5])$
Add comment
A non-backtracking version, David Landgren, 2005/12/02
The above patterns introduce unnecessary backtracking. If really want to use this approach, at least use a regular expression that doesn't backtrack, for efficiency reasons.
(?:1\d?\d?|2(?:[0-4]\d?|[6789]|5[0-5]?)?|[3-9]\d?|0)
If you expect to fail the expression most of the time, you can short-circuit the match completely with a look-ahead assertion:
(?=\d)(?:1\d?\d?|2(?:[0-4]\d?|[6789]|5[0-5]?)?|[3-9]\d?|0)
Add comment
The above matches one octet, David Landgren, 2005/12/02
Oops, I hit the Add button too soon. The above only matches one octet of an IP address. The pattern should of course read
(?:1\d?\d?|2(?:[0-4]\d?|[6789]|5[0-5]?)?|[3-9]\d?|0)(?:\.(?:1\d?\d?|2(?:[0-4]\d?|[6789]|5[0-5]?)?|[3-9]\d?|0)){3}
That is, an octet, followed by three occurrences of "dot followed by octet". If you're not bothered by the expense of capturing, it could be written more concisely as:
(1\d?\d?|2(?:[0-4]\d?|[6789]|5[0-5]?)?|[3-9]\d?|0)(?:\.\1){3}
Add comment
simple is sweeter, Michael Freeman, 2005/12/05
/^(\d{1,3}\.){3}\d{1,3}$/
Add comment
what about this line 2006.03.08.10.32.13 (date time)?, Mike Melnikov, 2006/03/08
in this "by mx.gmail.com with ESMTP id h1si582562nfe.2006.03.08.10.32.13" line
found "03.08.10.32"
Add comment
sasa sasa, 2006/09/04
\\
Add comment
|
|
|
|
|
 |
|