Select as many ips as possible inside 255 characters string

by Grzegorz Kulikowski

Imagine you have a lot of ips in array, but you want to divide them per 255 characters slices.  We join all them using a comma, and them replace comma by a semicolon

$ip4=1..30 | ForEach-Object { “192.168.1.$_” }
$ip4 -join ‘,’,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

$ip4 -join ‘,’ -replace ‘(\G.{216,255}),’,’$1;’,,,,,,,,,,,,,,,,,,,;,,,,,,,,,
$ip4 -join ‘,’ -replace ‘(\G.{216,255}),’,’$1;’ -split ‘;’ |%{‘Next result’;$_}Next result,,,,,,,,,,,,,,,,,,,
Next result,,,,,,,,,

We are aiming for the commas

We will replace a comma with our first group from the match and put a semicolon. Then we will be splitting strings on semicolons  since we know that at position of the semicolon was the position that could hold the maximum amount of ips in 255 char string area.

And let’s say we are interested only first two batches in case we got more than 30 ips
$ip4 -join ‘,’ -replace ‘(\G.{216,255}),’,’$1;’ -split ‘;’,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

$first,$second,$null = $ip4 -join ‘,’ -replace ‘(\G.{216,255}),’,’$1;’ -split ‘;’

Puts first batch to $first, second batch to $second and the rest goes to null.
This will work also with ipv6, the replace part of regex is greedy, so in case you will be working with ip6 and later with ip4, it will still find the maximum amount of ips. that’s why it has 216-255 instead of 240-255


You may also like

Leave a Reply

Chinese (Simplified)DutchEnglishFrenchGermanHindiPolishRussianSpanish
Streaming live on Twitch right now.