URL Manipulation: http://example.com/foo.jpg & # 8594; http://example.com/foo.preview.png

In rails, I want to write code to change this URL string

https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg

to

https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.png

Should I use a regex to change it?

I am new to Regexp, anyone can show me how to do this and how to find out this stuff.

thank

+3
source share
3 answers

If the extension has a fixed length, you'd better use a line string .

url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
print url[0..-5] + ".preview" + url[-4..-1]

exits

https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpg

Or, if your extensions are of variable length, you can use rindex()to find the beginning of the extension.

url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpeg"
dot_index = url.rindex(".")-1
print url[0..dot_index] + ".preview" + url[dot_index+1..-1]

exits

https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpeg

If you must use a regex, do the following:

url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpeg"
print url.gsub(/\.(\w{2,4})$/, ".preview.\\1")

exits

https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpeg
+4

, .jpg,

url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
url.gsub(".jpg", ".preview.jpg")

, .

url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
ext = File.extname(url)
url.gsub(ext, ".preview{ext}")
+4

A line break seems to be enough. ".jpg" → ".preview.png" Unfortunately, I do not know the ruby. In python, it will be

new_url = url.replace(".jpg",".preview.png",1)

I think it will look like a ruby. It seems to be sub().

new_url = url.sub(".jpg",".preview.png")
+1
source

Source: https://habr.com/ru/post/1781829/


All Articles