On 29/11/2010 14:22, Kammen van, Marco, Springer SBM NL wrote:
Dear List,
I've been struggeling with the following:
#!/usr/bin/perl
use strict;
use warnings;
my $ip = ("127.0.0.255");
if ($ip =~ /127\.0\.0\.[2..254]/) {
print "IP Matched!\n";;
} else {
print "No Match!\n";
}
For a reason i don't understand:
127.0.0.1 doesn't match as expected...
Everything between 127.0.0.2 and 127.0.0.299 matches...
127.0.0.230 doesn't match...
What am I doing wrong??
Thanks!
Hello Marco
Regular expressions can't match a decimal string by value. The regex
/[2..254]/ uses a character class which matches a SINGLE character,
which may be '2', '5', '4' or '.'. It is the same as /[254.]/ as
characters that appear a second time have no effect. To verify the value
of a decimal substring you need to add an extra test:
if ($ip =~ /^127\.0\.0\.([0-9]+)$/ and 2 <= $1 and $1 <= 254) {
:
}
In the case of a successful match, this captures the fourth sequence of
digits, leaving it in $1. This value can then be tested separately to
make sure it is in the desired range. Note that I have added the
beginning and end of line anchors ^ and $ which ensure that the the
string doesn't just contain a valid IP address, otherwise anything like
"XXX.127.0.0.200.300.400" would pass the test.
HTH,
Rob
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/