user1297102
user1297102

Reputation: 661

Replace every other character

how could i skip or replace every other character (could be anything) with regex?

"abc123.-def45".gsub(/.(.)?/, '@')

to get

"a@c@2@.@d@f@5"

Upvotes: 3

Views: 1440

Answers (3)

Anand Shah
Anand Shah

Reputation: 14913

The below code will also work:

irb(main):005:0> "abc123.-def45".chars.each_with_index.map {|e,i| !i.even? ? e = "@" : e}.join
=> "a@c@2@.@d@f@5"

Upvotes: 1

Martin Ender
Martin Ender

Reputation: 44289

Capture the first character instead, and write it back:

"abc123.-def45".gsub(/(.)./, '\1@')

It's important that you don't make the second character optional. Otherwise, in an odd-length string, the last character would lead to a match, and a @ would be appended. Without the ?, the last character will simply fail and remain untouched.

Working demo.

Upvotes: 5

ARMBouhali
ARMBouhali

Reputation: 298

You can also do this to avoid replacing @ in sequences

"abc123.-def45".gsub(/([^@])[^@]/, '\1@')

Upvotes: 1

Related Questions