Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
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"
而是捕获第一个字符,并将其写回:
"abc123.-def45".gsub(/(.)./, '\1@')
不要将第二个字符设为可选,这一点很重要。否则,在奇数长度的字符串中,最后一个字符将导致匹配,并且@将附加 a。如果没有?,最后一个字符将简单地失败并保持不变。
@
?
工作演示。
下面的代码也可以工作:
irb(main):005:0> "abc123.-def45".chars.each_with_index.map {|e,i| !i.even? ? e = "@" : e}.join => "a@c@2@.@d@f@5"
您也可以这样做以避免在序列中替换 @
"abc123.-def45".gsub(/([^@])[^@]/, '\1@')