From: Janus Bor Date: 2008-08-17T01:46:45+09:00 Subject: Re: Alternative for look behind Thanks to both of you! I like your solutions. I'm a fan of one liners... I ended up using this one, as it has the best readability for a novice programmer like me imho: Robert Klemme wrote: > irb(main):011:0> sequence.sub(/^-*/) {|m| "X" * m.length} > => "XXXXXXXabcde-gh----" Robert Klemme wrote: > It does - in 1.9. But: > > irb(main):001:0> sequence = '-------abcde-gh----' > => "-------abcde-gh----" > irb(main):002:0> sequence.gsub(/(?=^-*)-/, "X") > => "X------abcde-gh----" Thanks for the info. Just downloaded 1.9 to check it out. But I still don't comprehend why look behind is not working like I expected. If I write the equivalent replacing characters at the end of the string using look ahead it works just fine: irb(main):001:0> sequence = '-------abcde-gh----' => "-------abcde-gh----" irb(main):002:0> sequence.gsub(/-(?=-*$)/, "X") => "-------abcde-ghXXXX" Robert Klemme wrote: > I am not sure lookbehind is the proper means here. After all you want > to replace a sequence of dashes *before* a particular sequence > (according to your description above). So you would rather use > lookforward, wouldn't you? > > irb(main):003:0> sequence.gsub(/-(?=-*abcde)/, "X") > => "XXXXXXXabcde-gh----" > > Granted, it does not anchor. The problem with look ahead/forward is, that I have to make sure the sequence starts with "-". Otherwise something like this could happen: irb(main):003:0> sequence = 'abcde-gh----' => "abcde-gh----" irb(main):004:0> sequence.gsub(/-(?=-*[abcdefgh])/, "X") => "abcdeXgh----" Kind regards, Janus -- Posted via http://www.ruby-forum.com/.