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

前端 未结 10 1153
南笙
南笙 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:49

    "abc123abc123".gsub(/(.*(abc.*)*)(abc)(.*)/, '\1ABC\4')
    #=> "abc123ABC123"
    

    But probably there is a better way...

    Edit:

    ...which Chris kindly provided in the comment below.

    So, as * is a greedy operator, the following is enough:

    "abc123abc123".gsub(/(.*)(abc)(.*)/, '\1ABC\3')
    #=> "abc123ABC123"
    

    Edit2:

    There is also a solution which neatly illustrates parallel array assignment in Ruby:

    *a, b = "abc123abc123".split('abc', -1)
    a.join('abc')+'ABC'+b
    #=> "abc123ABC123"
    

提交回复
热议问题