Generally, you can't get an arbitrary number of capturing groups, but if you use scan
you can get a match for every token you want to capture:
a = "%span.rockets#diamonds.ribbons.forever"
a = a.scan(/^%\w+|\G[.|#]\w+/)
puts a.inspect
["%span", ".rockets", "#diamonds", ".ribbons", ".forever"]
This isn't too different from your regex, but I removed repetition on the last token. \G
isn't too well known - it tells the engine to match where the previous match ended, so it doesn't break when you have extra characters between matches (%span :P .rockets
).
Generally, if you had multiple matches of your original regex this method may add some work, because you don't have the groups separated to matches, but since match
returns a single result it should work fine.
Working example: http://ideone.com/nnmki