简体   繁体   English

替换所有其他角色

[英]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"

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. 工作演示。

您也可以这样做以避免在序列中替换@

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

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM