From: Bruno Michel Date: 2006-09-29T19:23:13+09:00 Subject: Re: Regexp help Vincent Fourmond a �crit : > Hello again ! > >>> I have a string of the form >>> >>> 2h 3m >>> >>> or >>> >>> 3m 2h >>> [....] >>> Is there a smart regexp one liner that could produce >>> >>> [2, 3] >> If you want to get [2,3] in both cases, that will be really difficult. >> As far as I know, you can only do that in C#, which has named capturing >> groups. In all the other languages I know, the capturing groups are >> numbered when they are found... That rules it out. > > Well, just to contradict myself, although this is no one-liner: > > def scan(str) > re = Regexp.new(/(\d+)h.*(\d+)m|(\d+)m.*(\d+)h/) > if m = re.match(str) > return [m[1], m[2]] if m[1] > return [m[4], m[3]] > end > end > > p scan("2h 3m") > p scan("3m 2h") > > Cheers ! > > Vince > And the one-liner : $ irb >> "3m 2h".scan(/(\d+)h.*(\d+)m|(\d+)m.*(\d+)h/).flatten.values_at(0,1,3,2).compact => ["2", "3"] >> "2h 3m".scan(/(\d+)h.*(\d+)m|(\d+)m.*(\d+)h/).flatten.values_at(0,1,3,2).compact => ["2", "3"] It's possible to add .map { |i| i.to_i } at the end of this one-liner if the result array must contain integers instead of strings. -- Bruno Michel