Perl regular expression to match an IP address

2019-01-26 07:40发布

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";
  if($ip =~ /(\d{1-3}\.\d{1-3}\.\d{1-3}\.\d{1-3}\:\d{1-5})/)
  {
      print "$1\n";
  }
}

EDIT: I wanted to just extract the IP address, not do any validation.

标签: regex perl ip
12条回答
趁早两清
2楼-- · 2019-01-26 07:48

http://metacpan.org/pod/Regexp::Common::net

If you extract an IP address that is not an IP address... you are not extracting the right thing.

查看更多
祖国的老花朵
3楼-- · 2019-01-26 07:51
$ip = "10.255.256.1";

# will accept valid ips
if ($ip =~ m/^([1|2][0-9]{1,2})\.([0-255]{1,3}\.){2}[0-255]{1,3}/ && ($1 <=255)) {

  print "This is a valid ip: $ip \n";
 } else {
   print "This is not a valid ip: $ip \n";
}
查看更多
SAY GOODBYE
4楼-- · 2019-01-26 07:52

This might help:

my $ip = "195.249.61.14";

my @ips = (
    "set protocols bgp group IBGP-RRCL-CUSTOMER neighbor 195.249.61.142",
    "set protocols bgp group IBGP-RRCL-CUSTOMER neighbor 195.249.61.14",
    "set protocols bgp group IBGP-RRCL-CUSTOMER neighbor 195.249.61.141"
);

foreach (@ips) {
   print "$_\n" if ( /\b$ip\b/ );
}

Output:

set protocols bgp group IBGP-RRCL-CUSTOMER neighbor 195.249.61.14
查看更多
劳资没心,怎么记你
5楼-- · 2019-01-26 07:52
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";
}
}
查看更多
欢心
6楼-- · 2019-01-26 07:54

You can also use the following regex to make sure that the quad's aren't bigger then 255, it also "reuses" the digit matching instead of copypasting it 4 times.

my $rx = qr/^(?!(\.))(\.?(\d{1,3})(?(?{$^N > 255})(*FAIL))){4}$/;
if('192.168.1.2' =~ $rx){
  print "OK\n";
}

It uses a few features from perl regex matching (man perlre):

  • (*FAIL): stops pattern matching and fails
  • (?(condition)...): conditional match
  • (?{ code }): used within that condition
查看更多
做个烂人
7楼-- · 2019-01-26 07:55

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

查看更多
登录 后发表回答