I would like to create a Ruby pattern to replace all but the last occurrence of a letter.
For example, replace all:
"}"
with the string:
"} something "
Turn this string:
"{ anything } { anything } { anything }"
to:
"{ anything } something { anything } something { anything }"
EDIT:
What I've used so far:
replaceString = "} something"
string.gsub("}", replaceString).reverse.sub(replaceString.reverse, "}").reverse
but I don't think it is very effective.
You can use positive lookahead:
str = "{ anything } { anything } { anything }"
pattern = /\}(?=.*\})/
str.gsub(pattern, "} Something")
=> "{ anything } Something { anything } Something { anything }"
In my other answer I didn't tell you that regex is an overkill for such a simple problem, not to mention that it is probably the slowest possible solution.
I would prefer a simple tailored solution like this one:
def replace_all_but_last str, substr1, substr2
str.dup.tap { |result|
index = str.rindex substr1
result[0...index] = result[0...index].gsub(substr1, substr2)
}
end
str = "{ anything } { anything } { anything }"
replace_all_but_last str, "}", "} something"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.