Reputation: 661
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
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
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.
Upvotes: 5
Reputation: 298
You can also do this to avoid replacing @ in sequences
"abc123.-def45".gsub(/([^@])[^@]/, '\1@')
Upvotes: 1