From: ara.t.howard@... Date: 2006-07-13T04:31:46+09:00 Subject: Re: Help with a regexp On Thu, 13 Jul 2006 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? the second. it's invalid here 2:ab23:cat ^ ^ virtual position 10. harp:~ > cat a.rb require 'strscan' class List < ::Array def initialize s parse s end class ParseError < ::StandardError; end def parse s clear ss = StringScanner.new s.to_s until ss.eos? n = ss.scan %r/^\d+:/ raise ParseError, "syntax error beginning @ pos <#{ ss.pos }>" unless n n = n.to_i raise RangeError, "bad length <#{ n }>" if n < 0 word = ss.scan(%r/.{0,#{ n }}/).to_s raise ParseError, "syntax error beginning @ pos <#{ ss.pos }>" unless word.size == n self << word end end end list = List.new "3:ab23:cat5:sheep" p list list = List.new "2:ab23:cat" p list harp:~ > ruby a.rb ["ab2", "cat", "sheep"] a.rb:20:in `parse': syntax error beginning @ pos <10> (List::ParseError) from a.rb:5:in `initialize' from a.rb:31 regards. -a -- suffering increases your inner strength. also, the wishing for suffering makes the suffering disappear. - h.h. the 14th dali lama