Perl regular expression to match an IP address

前端 未结 11 1592
独厮守ぢ
独厮守ぢ 2020-12-11 02:52

I have written this code, but it does not work. Can someone point out the issue?

sub match_ip()
{
  my $ip = \"The IP address is 216.108.225.236:60099\";
  i         


        
相关标签:
11条回答
  • 2020-12-11 03:05

    Alternatively, you can use Data::Validate::IP, with the caveat that it won't recognize the port, so you'll have to split on :.

    use strict;
    use warnings;
    use Data::Validate::IP;
    
    my $ip_with_port="216.108.225.236:60099";
    my $ip=(split /:/,$ip_with_port)[0];
    
    my $validator=Data::Validate::IP->new;
    
    if($validator->is_ipv4($ip))
    {
      print "Yep, $ip is a valid IPv4 address.\n";
    }
    else
    {
      print "Nope, $ip is not a valid IPv4 address.\n";
    }
    

    The output is:

    Yep, 216.108.225.236 is a valid IPv4 address.
    
    0 讨论(0)
  • 2020-12-11 03:08

    In the spirit of TIMTOWTDI here is another: the Regexp::Common::net portion of Regexp::Common may have regexen that you desire.

    0 讨论(0)
  • 2020-12-11 03:08
    #!/usr/bin/perl
    
    $str = 'IP address is : 70.21.311.105';
    
        if ($str =~ m/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/) {
            if ($1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255 ) {
                print "Valid $str\n";
        } else {
              print "invalid IP $str\n";
        }
    }
    
    
    __END__
    
    0 讨论(0)
  • 2020-12-11 03:13
    use strict;
    use warnings;
    open(FH,"<fileName.txt") or die "file not found ,$_";
    while(my $line=<FH>)
    {
    push(my @arr,($line));
    foreach my $arrVal (@arr)
    {           
    if($arrVal=~/IPv4 Address(?=.*\b((25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2  [0-4]\d|[0-1]?\d?\d)){3})\b)/)
    {
    print "$arrVal\n";
    }
    }
    
    0 讨论(0)
  • 2020-12-11 03:18

    Try this:

    $variablename=~m/((((0-9)|((1-9)(0-9))|(1([0-9]){2})|(2[0-4][0-9])|(2[5][0-5]))\.){3})((0-9)|((1-9)(0-9))|(1([0-9]){2})|(2[0-4][0-9])|(25[0-5]))/)
    
    0 讨论(0)
提交回复
热议问题