From: Robert Klemme Date: 2006-12-07T18:05:06+09:00 Subject: Re: Get Number of regex matches On 06.12.2006 22:44, Martin DeMello wrote: > On 12/7/06, Max Muermann wrote: >> On 12/7/06, Ingo Weiss wrote: >> > Hi, >> > >> > how can I get the NUMBER of matches for a regular expression in a given >> > string? >> > >> > For example: for string 'Banana' and regex /a/ I should get '3' >> > (matches) >> > >> >> Here's one way (but there are probably better ones): >> >> "Banana".scan(/a/).size >> => 3 > > This one skips the intermediate array construction in return for some > clunkiness: > > i = 0 > banana.scan(/a/) { i += 1} > i >> require 'enumerator' => true >> "banana".to_enum(:scan, /a/).inject(0) {|s,| s+1} => 3 :-) robert