开发者

Replace using gsub

开发者 https://www.devze.com 2023-03-10 06:29 出处:网络
I\'m having som开发者_Python百科e problem replacing a partial of a string with another string. I want this string \"this-is-a-string.jpg\" to be replaced with \"this-is-a-hash.jpg\".

I'm having som开发者_Python百科e problem replacing a partial of a string with another string.

I want this string "this-is-a-string.jpg" to be replaced with "this-is-a-hash.jpg". The string value can be any value.

This is what I've so far.

str = "this-is-a-string.jpg"
str.gsub(/([a-z]+)[^\.]+?$/i, "hash")
# => "this-is-a-string.hash"


I played around with rubular and I came up with a regexp which works if you don't mind adding a dot manually to the replacement.
Here is what I came up with

"this-is-a-string.jpg".gsub(/\w+\./, 'hash.')

So I guess you could make a simple function which replaces it like

def replace_string(string_to_replace, replacement)
  string_to_replace(/\w+\./, "#{replacement}.")
end

in ruby 1.9.2 I managed to extract the word "string" but I don't know if that is of any use to you.

  /[-\w]+\-(?<word>(\w+))\.\w+/ =~ "this-is-a-string.jpg"
=> 0
  word
=> "string"

I hope I've helped you and given the information you needed

0

精彩评论

暂无评论...
验证码 换一张
取 消