I have strings like bright orange bags contain 5 faded olive bags, 5 posh tomato bags, 1 plain green bag.
I want to extract the colour of the containing bag, and the number and colours of the contained bags. So my ideal output would contain ['bright orange', '5', 'faded olive', '5', 'posh tomato', '1', 'plain green']
.
I've tried the following regex, but is isn't giving me what I want:
/^(\w+ \w+) bags contain (?:(\d+) (\w+ \w+) bag(?:s.|.|s, |, ))+$/
That gets me
["bright orange bags contain 5 faded olive bags, 5 posh tomato bags, 1 plain green bag.", "bright orange", "1", "plain green"]
Which is the container colour and the last contained quantity and colour.
If I change the +
to a specific number, e.g. {2}
, then I get the correct output for strings with exactly that number of matches, but I don't want to do n regex where n is the maximum number of matches, and {1,n}
gives the same result as +
.
I've looked at this question but its answer specifies a number.
Is there a regex to output every time the group matches?
(I've specified JavaScript because I know is does regex differently in some circumstances)