How to replace the last occurrence of a substring

2020-05-29 16:16发布

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 to ABC. How do I do that?

标签: ruby
10条回答
Fickle 薄情
2楼-- · 2020-05-29 16:52

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"
查看更多
The star\"
3楼-- · 2020-05-29 16:56

You can achieve this with String#sub and greedy regexp .* like this:

'abc123abc123'.sub(/(.*)abc/, '\1ABC')
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-05-29 16:58
string = "abc123abc123"
pattern = /abc/
replacement = "ABC"

matches = string.scan(pattern).length
index = 0
string.gsub(pattern) do |match|
  index += 1
  index == matches ? replacement : match
end
#=> abc123ABC123
查看更多
倾城 Initia
5楼-- · 2020-05-29 16:59
.gsub /abc(?=[^abc]*$)/, 'ABC'

Matches a "abc" and then asserts ((?=) is positive lookahead) that no other characters up to the end of the string are "abc".

查看更多
登录 后发表回答