Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Saving Repeating Captured Group

This is what I'm doing

a = "%span.rockets#diamonds.ribbons.forever"
a = a.match(/(^\%\w+)([\.|\#]\w+)+/)
puts a.inspect

This is what I get

#<MatchData "%span.rockets#diamonds.ribbons.forever" 1:"%span" 2:".forever">

This is what I want

#<MatchData "%span.rockets#diamonds.ribbons.forever" 1:"%span" 2:".rockets" 3:".#diamonds" 4:".ribbons" 5:".forever">

help? I tried and failed :(

like image 378
Andrew Brown Avatar asked Sep 06 '10 02:09

Andrew Brown


2 Answers

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

like image 160
Kobi Avatar answered Oct 11 '22 09:10

Kobi


That's just how capturing groups work. If you want to save all of those substrings, put the quantifier inside the capturing group:

a = a.match(/(^%\w+)((?:[.#]\w+)+)/)

Then your second capture will be:

2:".rockets#diamonds.ribbons.forever"

...and you can break it down the rest of the way yourself.

like image 40
Alan Moore Avatar answered Oct 11 '22 08:10

Alan Moore