On Jul 12, 2006, at 2:54 PM, dblack / wobblini.net wrote:

> Hi --
>
> On Thu, 13 Jul 2006, Daniel Schierbeck wrote:
>
>> My problem is that I have a string like this:  
>> "3:foo6:monkey5:sheep", which I need to separate into ["foo",  
>> "monkey", "sheep"]. The values can contain numeric values, so  
>> splitting at \d won't work. This is what makes it difficult:
>>
>>  "3:ab23:cat5:sheep" => ["ab2", "cat", "sheep"]
>>
>> I need to grab the number, then read that many characters, then  
>> read the next number, etc.
>
> How do you know, in the case of:
>
>   2:ab23:cat
>
> which of the two is invalid?
>
>
> David
>

I don't believe you do. OTOH I'm not sure if you should care. If  
one's invalid, the whole thing is invalid.

Anyway, here's my solution:

% cat n_colon_s.rb
require 'strscan'
def parse_n_colon_s(s)
   scanner = StringScanner.new(s)
   results = []
   until scanner.empty?
     if scanner.scan(/(\d+):/)
       n = scanner[1].to_i
       raise 'Malformed String' unless (s = scanner.scan(/\w{#{n}}/))
       results << s
     else
       raise 'Malformed string'
     end
   end
   results
end

p parse_n_colon_s("2:ab3:cat")
p parse_n_colon_s("2:ab23:cat")


% ruby n_colon_s.rb
["ab", "cat"]
-:18:in `parse_n_colon_s': Malformed String (RuntimeError)
	from -:28




> -- 
> http://www.rubypowerandlight.com => Ruby/Rails training & consultancy
> http://www.manning.com/black     => RUBY FOR RAILS, the Ruby book for
>                                                     Rails developers
> http://dablog.rubypal.com        => D[avid ]A[. ]B[lack's][ Web]log
> dblack / wobblini.net              => me
>