如何在perl中解析一个字符串?

How to parse a string in perl?

我有一个字符串,它是一个 IP 地址列表和一个重要的数字。

我正在尝试解析该字符串,使其仅包含 IP 地址。或者更好的是,根据表示的 IP 地址数量创建多个字符串。

我觉得我很接近,但没有雪茄。

输入:

$str = "[11.22.33.44]-30,[55.66.77.88]-30"

预期输出:

11.22.33.44
55.66.77.88

我第一次使用正则表达式解决这个问题:

while ($tempBlackList =~ /(\w+)/g) {
    print "\n";
}

这导致:

11
22
33
44
30
55
66
77
88
30

试图解决这个问题的第二次迭代:

while ($tempBlackList =~ /(\w+)(\w+)(\w+)(\w+)/g) {
    print "\"...\n";
}

这将导致不打印任何内容。我希望它是我想要的。

如有任何帮助,我们将不胜感激。

/(\w+)(\w+)(\w+)(\w+)/g 模式匹配四次连续出现的 \w+ 模式匹配一​​个或多个不包含点的单词字符(点不是单词字符)。

如果您在组之间插入 \.,该方法将起作用:

while ($tempBlackList =~ /(\w+)\.(\w+)\.(\w+)\.(\w+)/g) {
    print "...\n";
}

不过,这里你可以直接使用

my $tempBlackList = "[11.22.33.44]-30,[55.66.77.88]-30";
while ($tempBlackList =~ /\[([^][]+)]/g) {
    print "\n";
}

输出:

11.22.33.44
55.66.77.88

参见 this Perl demo

但是,因为IP regex是一个众所周知的模式,你可以用它来提取所有出现的地方:

my $tempBlackList = "[11.22.33.44]-30,[55.66.77.88]-30";
while ($tempBlackList =~ /\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?2)){3})\b/g) {
    print "\n";
}

this Perl demo