How to replace the last occurrence of a substring in ruby?

前端 未结 10 1152
南笙
南笙 2021-02-03 20:08

I want to replace the last occurrence of a substring in Ruby. What\'s the easiest way? For example, in abc123abc123, I want to replace the last abc

10条回答
  •  失恋的感觉
    2021-02-03 20:59

    How about

    new_str = old_str.reverse.sub(pattern.reverse, replacement.reverse).reverse
    

    For instance:

    irb(main):001:0> old_str = "abc123abc123"
    => "abc123abc123"
    irb(main):002:0> pattern="abc"
    => "abc"
    irb(main):003:0> replacement="ABC"
    => "ABC"
    irb(main):004:0> new_str = old_str.reverse.sub(pattern.reverse, replacement.reverse).reverse
    => "abc123ABC123"
    

提交回复
热议问题