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

前端 未结 10 1151
南笙
南笙 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 21:05

    Since Ruby 2.0 we can use \K which removes any text matched before it from the returned match. Combine with a greedy operator and you get this:

    'abc123abc123'.sub(/.*\Kabc/, 'ABC')
    #=> "abc123ABC123"
    

    This is about 1.4 times faster than using capturing groups as Hirurg103 suggested, but that speed comes at the cost of lowering readability by using a lesser-known pattern.

    more info on \K: https://www.regular-expressions.info/keep.html

提交回复
热议问题