From: Robert Klemme Date: 2005-12-15T19:07:39+09:00 Subject: Re: string mangling Martin Pirker wrote: > Robert Klemme wrote: >>> Imagine an input string >>> aaaaabbccccceeebbbbbbbbbbeaaabaacccceeee... >>> >>> I have regexp for the parts a,b,c >>> and e can be considered as else. >>> >>> So how can I efficiently search/step through the string from left to >>> right, while calling for each section the fitting handler, kind of >>> >>> case section >>> /aaaa/ ... >>> >>> /bbb/ ... >>> >>> /cccc/ .. >>> >>> else >>> >>> end > [...] >> Or, if you want to avoid a second match: > > of course I want :-) > >>>> s.scan /(a+)|(b+)|(c+)/ do |m| >>> case ( m.inject(0) {|i,e| break i if e; i + 1} ) >>>> when 0 >>>> puts "A" >>>> when 1 >>>> puts "B" >>>> when 2 >>>> puts "C" >>>> end >>>> end >> A >> B >> C >> B >> A >> B >> A >> C >> => "aaaaabbccccceeebbbbbbbbbbeaaabaacccceeee" > > ...but this doesn't allow a processing step in the "else" case? You can have an else clause - but it will never be called. I guess you will process entries between matches. In that case scan won't help - at least not as used in my example. A simple option would be to use #split with a group around the whole regexp and then operate on the array of strings you get. Whether that's feasible (volume?) in you case I cannot decide. s.split(/((?:a+)|(?:b+)|(?:c+))/.each do |m| case section /aaaa/ ... /bbb/ ... /cccc/ .. else end end Kind regards robert