1

I have a string that is a list of IP addresses and an important number.

I'm trying to parse the string, such that it only includes the IP address. Or better yet, create multiple strings depending on how many IP addresses are denoted.

I feel like I'm close, but no cigar.

Input:

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

Expected Output:

11.22.33.44
55.66.77.88

My first iteration at solving this using regex:

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

This results in:

11
22
33
44
30
55
66
77
88
30

Second Iteration of trying to solve this:

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

This results in nothing being printed. I expected it to be what I wanted.

Any help would be appreciated.

1 Answers1

2

The /(\w+)(\w+)(\w+)(\w+)/g pattern matches four consecutive occurrences of the \w+ pattern that matches one or more word chars that do not include a dot (a dot is not a word char).

If you insert \. in between the groups, that approach will work:

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

However, here you can just use

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

Output:

11.22.33.44
55.66.77.88

See this Perl demo.

However, since the IP regex is a well-known pattern, you may use it to extract all occurrences:

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 "$1\n";
}

See this Perl demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563