# Is there way to replace n occurrences starting from the end of a string?

Let’s say you have:

``````foo = "fizz_buzz_fizz_buzz_fizz_buzz_fizz_buzz_fizz_buzz"
``````

and you want to change the last two buzzes to bars:

``````nu_foo = "fizz_buzz_fizz_buzz_fizz_buzz_fizz_bar_fizz_bar"
``````

What is the easiest way to do this with the least code.

For clarity, this would be the opposite of the current replace function with an limit count given:

``````julia> replace(foo, "buzz", "baz", 2)

"fizz_baz_fizz_baz_fizz_buzz_fizz_buzz_fizz_buzz"
``````

In case nothing better is found, a rookery of reversions could do the trick

`````` reverse(replace(reverse(foo), reverse("buzz") => reverse("baz"), count=2))
"fizz_buzz_fizz_buzz_fizz_buzz_fizz_baz_fizz_baz"
``````
2 Likes

I think this is the way to go, even if there’s a function for OP, probably would just be a wrapper

Yup, that’s the way to do it:

``````function rreplace(varargs...; kwargs...)
varargs = map(
vararg -> isa(vararg, AbstractString) ? reverse(vararg) : vararg,
varargs
)

reverse(replace(varargs...;kwargs...))
end
``````

be careful:

``````julia> rreplace(foo, r"b.zz"=>"baz", count=2)
"fizz_buzz_fizz_buzz_fizz_buzz_fizabuzz_fizabuzz"
``````
2 Likes

I’ll leave that as an exercise for the reader

Another option, more concise and efficient than the previous:

``````julia> join(rsplit(foo, "buzz", limit=3), "baz")
"fizz_buzz_fizz_buzz_fizz_buzz_fizz_baz_fizz_baz"
``````

According to the documentation, this solution should also support regexes, but the code for that seems to be missing.

1 Like