http://www.perlmonks.org?node_id=1013903


in reply to Split file using perl and regexp

Here's an approach based on the observation of certain similarities (common prefix characters) in the data fields of interest in the three different types of data files. No discrimination between the three data file types is needed in the code.

Some notes of caution:

>perl -wMstrict -le "my @records = ( '1|1212|34353|56575|||||4|~some~~pi=[10.10.10.10.10],uid=[11]}~', '1|1212|34353|56575|||||4|~som~~390=10.10.10.10.11,391=222,394~', '1|1212|34353|56575|||||4|~somedata~10.10.10.10.12~3333~~a~~~~', ); ;; my $rx_oct = qr{ \d{1,3} }xms; my $rx_quint = qr{ $rx_oct (?: \. $rx_oct){4} }xms; ;; my $rx_dotted = qr{ (?<! \d) $rx_quint (?! \d) }xms; my $rx_int = qr{ \d+ }xms; ;; for my $record (@records) { print qq{'$record'}; my ($const, $var) = $record =~ m{ ( \A .+) \| ( .* \z) }xms; my (undef, $dotted, $int) = $var =~ m{ (\D) ($rx_dotted) .*? \1 ($rx_int) }xms; my $new_record = join '|', $const, $dotted, $int; print qq{'$new_record' \n}; } " '1|1212|34353|56575|||||4|~some~~pi=[10.10.10.10.10],uid=[11]}~' '1|1212|34353|56575|||||4|10.10.10.10.10|11' '1|1212|34353|56575|||||4|~som~~390=10.10.10.10.11,391=222,394~' '1|1212|34353|56575|||||4|10.10.10.10.11|222' '1|1212|34353|56575|||||4|~somedata~10.10.10.10.12~3333~~a~~~~' '1|1212|34353|56575|||||4|10.10.10.10.12|3333'

Update: After playing around with this a bit and doing a little, um, testing, I think I would change the definition of  $rx_dotted as follows (change to final look-ahead):
    my $rx_dotted = qr{ (?<! \d) $rx_quint (?! [.\d]) }xms;
This change does not affect behavior for valid records.