What regex can I use to match any valid IP-address

2019-04-06 10:40发布

问题:

What regex can I use to match any valid IP-address represented in dot-decimal notation?

回答1:

CPAN is your friend: Regex::Common or Net::IP::Match::Regexp.



回答2:

if($ip=~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ &&(($1<=255  && $2<=255 && $3<=255  &&$4<=255 )))
     {
         print "valid\n";
     }
     else
     {
         print "Invalid\n";
     }


回答3:

I like this one ... pretty much as Steve Hajducko's but using quoted reg ex which rooooock!

my $ip = '120.140.255.254'; # for example

my $ipno = qr/
    2(?:5[0-5] | [0-4]\d)
    |
    1\d\d
    |
    [1-9]?\d
/x;

if ( $ip =~ /^($ipno\.){3}$ipno$/ ){
    print "IP OK\n";
};

I went for an interview at Arm in Cambridge, UK. They asked me to write one on the board and I wrote some lame one .. and later ... brooding on my poor attempt set out to make a better one. Driven by failure? Or maybe just really irritated by it. I still got the job :)



回答4:

How do I write a regular expression that matches an IPv4 dotted address?

Long story short: Don't do it ^^.



回答5:

If you can leave a perl module behind - then do it.

what about:

if( $ip=~ m/^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)/ && 
          ( $1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255 )
) {    
    print "valid IP.";
}


回答6:

For IPv4 in an A.B.C.D (decimal) format, as a one-liner:

(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])

If nothing follows the address on the line, it can be contracted to:

(?:(?:[01]?\d?\d?|2[0-4]\d|25[0-5])(?:\.|$)){4}

Have fun.



回答7:

(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])

Actually matches some invalid IP addresses, such as:

192.168.00.001

A slightly more refined solution would be:

(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$


回答8:

IPv4 ip validation with port number

if ( $ip =~ /(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(:(\d{1,5}))?/ )
{
    if( $1 > 255 || $2 > 255 || $3 > 255 || $4 > 255)
    {
        print "invalid ip\n";
        return ;
    }
    if( ( defined $6) && ( $6 > 65536 ))
    {
        print "invalid port\n";
        return ;
    }
    print "valid ip \n";
}
else
{
    print "invalid ip\n";
    return ;
}


回答9:

$ip='123.0.0.1';
if($ip=~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ &&((($1<=255 && $1 > 0) && $2<=255 && $3<=255  &&$4<=255 )))
 {
     print "valid\n";
 }
 else
 {
     print "Invalid\n";
 }

Blockquote

Here in this case we are validating 0.0.0.0 will not be consider the valid IP. and supporting all remaing IP's upto 1.0.0.0 to 255.255.255.255`enter code here

Blockquote



回答10:

Not sure why I don't see this one around anywhere, it's short, concise, and awesome.

([0-9]{1,3}\.){3}[0-9]{1,3}