Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re: Regular Expression - delimiter/spaces problem

by Util (Priest)
on Feb 14, 2014 at 21:50 UTC ( #1075007=note: print w/replies, xml ) Need Help??

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


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
    Thanks a lot for your solution. I tried and it worked fine. I have questions regarding the dash_or_digit reg.

    my $dash_or_digits     = qr{ (?: - | \d+ ) }msx

    Why are using (?:)?

    I never used this expression before and checked but it is not clear why use it. I tried it without and it worked also:

    my $dash_or_digits     = qr{ - | \d+  }msx

    Can you please let me know the reason? Thank you.

    regards deMichi
      Why are using (?:)?

      The "?:" reduces the parens effect to grouping. That means, the content of the parens will not be captured to populate a $< digit> variable ($1, $2, $3, ...). It is good practice to state exactly what is meant; and if you want to just group alternatives, then (?:) is the fitting expression.

      perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1075007]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (1)
As of 2021-10-21 03:11 GMT
Find Nodes?
    Voting Booth?
    My first memorable Perl project was:

    Results (82 votes). Check out past polls.