如何替换 ruby 中最后一次出现的子字符串? [英] How to replace the last occurrence of a substring in ruby?
问题描述
我想替换 Ruby 中最后一次出现的子字符串.最简单的方法是什么?例如,在abc123abc123中,我想将最后一个abc替换为ABC.我该怎么做?
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 2.0 开始,我们可以使用 \K
从返回的匹配项中删除在它之前匹配的任何文本.结合贪婪的运算符,你会得到这个:
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"
这比 Hirurg103 建议的使用捕获组快约 1.4 倍,但这种速度是以使用鲜为人知的模式降低可读性为代价的.
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.
关于 \K
的更多信息:https://www.regular-expressions.info/keep.html
这篇关于如何替换 ruby 中最后一次出现的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!