I seem to be having trouble constructing a regex that I'm sure ought to be straightforward.

I want to read lines from a file which contain one or more alphanumeric characters, followed by either 2 or 4 positive real numbers, separated by white space. For example:

Abc 	21223.7   21225.33   22270.3   22280.1
Def	21600.23  24567.43

The only regexp I've managed to come up with which does what I want is:

m/^(\w+)\s+([\d\.]+)\s+([\d\.]+)(?:\s+([\d\.]+)\s+([\d\.]+))?/

but I feel sure that there must be something shorter and more elegant.

I tried using:

m/^(\w+)(?:\s+([\d\.]+)\s+([\d\.]+)){1,2}/
Which works when there are two numbers, but puts the last two numbers into $2 and $3, throwing away the first two numbers from lines with four numbers (higher number variables are all empty).

If I remove the ?: the same thing happens but in $3 and $4.


In reply to Matching a pattern two or four times by Bilbo

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.