gpt4 book ai didi

regex - 如何从文件中提取一行中存在的所有 IP 地址?

转载 作者:行者123 更新时间:2023-12-05 09:27:04 27 4
gpt4 key购买 nike

我有一个包含一些信息的文件,包括如下所示的 IP 地址(一行可能包含多个 IP):

ip_group1,1.2.3.4,otherstring1,otherstring2,4.5.6.7
ip_group2,3.4.5.6,otherstring1
ip_group3,11.21.31.41,otherstring1,otherstring2,4.5.6.7,otherstring4,1.2.3.4,otherstring5,otherstring2,41.51.16.71

我正在使用这部分 Perl 代码来提取 IP,但它只提取第一次出现的 IP,而将其他 IP 保留在行中并处理下一个。

use Regexp::Common qw/net/;
while (<>) {
print $1, "\n" if /($RE{net}{IPv4})/;
}

如何获取一行中出现的所有 IP?

我的预期输出如下:

ip_group1,1.2.3.4,4.5.6.7
ip_group2,3.4.5.6
ip_group3,11.21.31.41,4.5.6.7,1.2.3.4,41.51.16.71

最佳答案

如果在while循环中进行全局匹配(//g),可以得到所有的IP地址:

use warnings;
use strict;
use Regexp::Common qw/net/;

while (<DATA>) {
my ($grp) = /^(\w+)/;
my @ips;
while (/($RE{net}{IPv4})/g) {
push @ips, $1;
}
print join(',', $grp, @ips), "\n";
}
__DATA__
ip_group1,1.2.3.4,otherstring1,otherstring2,4.5.6.7
ip_group2,3.4.5.6,otherstring1
ip_group3,11.21.31.41,otherstring1,otherstring2,4.5.6.7,otherstring4,1.2.3.4,otherstring5,otherstring2,41.51.16.71

打印:

ip_group1,1.2.3.4,4.5.6.7
ip_group2,3.4.5.6
ip_group3,11.21.31.41,4.5.6.7,1.2.3.4,41.51.16.71

关于regex - 如何从文件中提取一行中存在的所有 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72983993/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com