in reply to Regular Expression - delimiter/spaces problem
toolic++ ; By handling the first line separately, you can remove all the special cases that you had embedded in your regex, and thereby make it harder to mis-parse your data. The version below correctly handles whitespace in the second field.
Working, tested code:
#!/usr/bin/env perl use Modern::Perl; my $dash_or_digits = qr{ (?: - | \d+ ) }msx; my $string_with_spaces = qr{ \w [\s\w]*? }msx; my $re = qr{ \A \s* ( \d+ ) # PID \s+ ( $string_with_spaces ) # POLS \s+ ( \d+ ) # U(%) \s+ ( $string_with_spaces ) # POOL_NAME \s+ ( \d+ ) # Seq# \s+ ( \d+ ) # Num \s+ ( \d+ ) # LDEV# \s+ ( $dash_or_digits ) # H(%) \s+ ( $dash_or_digits ) # VCAP(%) \s+ ( \w+ ) # TYPE \s+ ( \w+ ) # PM \s* \z }msx; my $first_line = <DATA>; chomp $first_line; my @field_names = split ' ', $first_line; say join ';', @field_names; while ( <DATA> ) { chomp; my @fields = /$re/ or die; warn if scalar(@field_names) != scalar(@fields); say join ';', @fields; } __DATA__ PID POLS U(%) POOL_NAME Seq# Num LDEV# H(%) VCAP(%) TYPE PM 003 POLN 0 Bad name with spaces 13453 2 61443 80 - OPEN N 002 POLN 52 DemoSolutions 54068 7 61454 80 - OPEN N
Output:
PID;POLS;U(%);POOL_NAME;Seq#;Num;LDEV#;H(%);VCAP(%);TYPE;PM 003;POLN;0;Bad name with spaces;13453;2;61443;80;-;OPEN;N 002;POLN;52;DemoSolutions;54068;7;61454;80;-;OPEN;N
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Regular Expression - delimiter/spaces problem
by demichi (Beadle) on Feb 15, 2014 at 11:16 UTC | |
by shmem (Chancellor) on Feb 15, 2014 at 14:59 UTC |
In Section
Seekers of Perl Wisdom