【问题标题】:perl regex match all IPv4 addressperl 正则表达式匹配所有 IPv4 地址
【发布时间】:2016-05-05 22:05:30
【问题描述】:

我正在尝试删除列出的 IP 地址的 apache 状态页面,例如 apache status page

<tr><td><b>0-35</b></td><td>1791</td><td>1/1079/387615</td><td>G
</td><td>5541.08</td><td>379</td><td>557</td><td>135.0</td><td>33.04</td><td>20992.04
</td><td>83.60.245.1</td><td nowrap></td><td nowrap></td></tr>

我已经下载了页面

 #!/usr/bin/perl
    use strict;
    use warnings;
    use LWP::Simple;
    use feature 'say';
    use File::Slurp;
    my $content = get('http://www.apache.org/server-status') or die 'Unable to get page';

    write_file('filename',$content);

如何创建一组找到的 IP 地址?

谢谢

【问题讨论】:

标签: regex perl


【解决方案1】:

我会使用 CPAN 上的 RegExp::Common (Documentation) 模块,如下所示:

use Regexp::Common qw /net/;

while ($content =~ m!<td>($RE{net}{IPv4})</td>!g) {
  print "IP: $1\n";
}

【讨论】:

    【解决方案2】:

    只需找到以点分隔的 1-3 位数字组的所有条目,并验证每个条目是否在 0-255 范围内。

    while ($content =~ /(?<!\d)(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?!\d)/g) {
        if (
            $1 >= 0 && $1 <= 255 &&
            $2 >= 0 && $2 <= 255 &&
            $3 >= 0 && $3 <= 255 &&
            $4 >= 0 && $4 <= 255
        ) {
            print "$1.$2.$3.$4\n";
        }
    }
    

    【讨论】:

    • 使 1000.0.0.0 不被视为 IP 地址。
    • 不需要&gt;= 0 测试,因为您只匹配数字,所以不能有任何负数(破折号/负号与\d 不匹配)
    【解决方案3】:
    \d{1,3}(\.\d{1,3}){3}
    

    这不足以完全匹配所有 ipv4 地址,但对于您的页面来说应该足够了。

    例如,它也会匹配522.53.0.0

    演示:http://regexr.com/3dc1q

    【讨论】:

      猜你喜欢
      • 2016-01-31
      • 1970-01-01
      • 2012-04-27
      • 1970-01-01
      • 2018-02-27
      • 2010-12-20
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多