I can't see any good reason to use Parse::RecDescent to parse fixed width records. This would seem to be using a A-bomb to crack a walnut. Surely you would be better off to unpack the data into a structure and validate from there?

In addition to the examples above you can for fun autogenerate one that does the job you want - rather ugly but it does work.

for ( reverse 1..20 ) { $re .= sprintf "\\d{%d} {%d}|", $_, 20-$_; } chop $re; $re = qr/^(?:$re)$/; print $re, $/; @tests = ( '01234567890123456789', # OK '123 ', # OK '123 ', # NOK '123 123 ', # NOK ' ', # NOK '123c ', # NOK ); for(@tests){ print m/$re/ ? "'$_' #OK\n" : "'$_' #NOK\n" } __DATA__ (?-xism:^(?:\d{20} {0}|\d{19} {1}|\d{18} {2}|\d{17} {3}|\d{16} {4}|\d{ +15} {5}|\d{14} {6}|\d{13} {7}|\d{12} {8}|\d{11} {9}|\d{10} {10}|\d{9} + {11}|\d{8} {12}|\d{7} {13}|\d{6} {14}|\d{5} {15}|\d{4} {16}|\d{3} {1 +7}|\d{2} {18}|\d{1} {19})$) '01234567890123456789' #OK '123 ' #OK '123 ' #NOK '123 123 ' #NOK ' ' #NOK '123c ' #NOK

cheers

tachyon


In reply to Re: Regex to match 20 chars of some digits followed by some spaces by tachyon
in thread Regex to match 20 chars of some digits followed by some spaces by leriksen

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.