Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

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


In reply to Re: Regular Expression - delimiter/spaces problem by Util
in thread Regular Expression - delimiter/spaces problem by demichi

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (1)
As of 2021-12-05 20:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    R or B?



    Results (31 votes). Check out past polls.

    Notices?