Robert Klemme
8/16/2008 9:37:00 AM
On 16.08.2008 03:56, Janus Bor wrote:
> I need to replace all '-' characters at the beginning of a sequence
> (string) with 'X's (until a character appears that is not '-').
>
> E.g.
>
> -------abcde-gh----
>
> should be changed into
>
> XXXXXXXabcde-gh----
>
> If Ruby would support look behind in Regular Expressions, I could
> probably do something like this:
>
> sequence.gsub(/(?=^-*)-/, "X")
>
> But unfortunately Ruby does not support look behind.
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----"
irb(main):003:0>
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.
Here's another solution
irb(main):008:0> s = sequence.dup
=> "-------abcde-gh----"
irb(main):009:0> while s.sub! /^(X*)-/, '\\1X'; end
=> nil
irb(main):010:0> s
=> "XXXXXXXabcde-gh----"
But I'd rather use Pena's solution or another block form
irb(main):011:0> sequence.sub(/^-*/) {|m| "X" * m.length}
=> "XXXXXXXabcde-gh----"
irb(main):012:0> sequence.sub(/^-*/) {|m| m.tr '-','X'}
=> "XXXXXXXabcde-gh----"
Kind regards
robert