Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace every other character

Tags:

regex

ruby

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"
like image 254
user1297102 Avatar asked Nov 25 '25 01:11

user1297102


1 Answers

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.

like image 139
Martin Ender Avatar answered Nov 26 '25 16:11

Martin Ender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!