Jonas
Jonas

Reputation: 157

Ruby pattern match all but last

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.

Upvotes: 0

Views: 659

Answers (2)

Yossi
Yossi

Reputation: 12090

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"

Upvotes: 2

Yossi
Yossi

Reputation: 12090

You can use positive lookahead:

str = "{ anything }   { anything } { anything }"
pattern = /\}(?=.*\})/
str.gsub(pattern, "} Something")

=> "{ anything } Something   { anything } Something { anything }"

Upvotes: 2

Related Questions