Bilbo has asked for the wisdom of the Perl Monks concerning the following question:
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:
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).m/^(\w+)(?:\s+([\d\.]+)\s+([\d\.]+)){1,2}/
If I remove the ?: the same thing happens but in $3 and $4.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Matching a pattern two or four times
by LTjake (Prior) on Sep 24, 2002 at 11:54 UTC | |
|
Re: Matching a pattern two or four times
by RMGir (Prior) on Sep 24, 2002 at 12:22 UTC | |
by demerphq (Chancellor) on Sep 24, 2002 at 17:03 UTC | |
|
Re: Matching a pattern two or four times
by demerphq (Chancellor) on Sep 24, 2002 at 15:30 UTC | |
|
Re: Matching a pattern two or four times
by Bilbo (Pilgrim) on Sep 24, 2002 at 17:18 UTC | |
by RMGir (Prior) on Sep 24, 2002 at 17:43 UTC |