Crackers2 has asked for the wisdom of the Perl Monks concerning the following question:
I have a string like this:
$_ = "This is list number 12. It contains apples, pears, peaches. Total cost is 5.";
and I want to extract the elements of the list (apples, pears, peaches). I would like to do this using a single regex.
What I came up with is this:
my (@rep) = /It contains (?:\s*([^,]*),)*\s*([^\.]*)\./;
But even though this does match the text, @rep contains just pears and peaches.
Am I missing something trivial or should I just give up on the single regex idea and use multiples regexes and/or split to get what I want?
The example above is made up, but the actual strings look structurally the same: a preamble, followed by a variable number of <text><separator> pairs, followed by a postamble
Update: ikegami++ for the most practical solution, davido++ for a great single-regex solution
Update: pijll++ for doing both practical and single-regex
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Regex to extract multiple occurrences
by ikegami (Patriarch) on Sep 11, 2004 at 04:24 UTC | |
|
Re: Regex to extract multiple occurrences
by davido (Cardinal) on Sep 11, 2004 at 04:54 UTC | |
|
Re: Regex to extract multiple occurrences
by pijll (Beadle) on Sep 11, 2004 at 09:16 UTC | |
|
Re: Regex to extract multiple occurrences
by dragonchild (Archbishop) on Sep 11, 2004 at 03:43 UTC | |
by ikegami (Patriarch) on Sep 11, 2004 at 04:27 UTC | |
by Crackers2 (Parson) on Sep 11, 2004 at 04:20 UTC | |
|
Re: Regex to extract multiple occurrences
by dr3ad (Initiate) on May 30, 2022 at 05:27 UTC |