replace specific text in ruby using regex

150 Views Asked by At

In ruby, I'm trying to replace the below url's bolded portion with new numbers:

/ShowForum-g1-i12105-o20-TripAdvisor_Support.html

How would I target and replace the -o20- with -o30- or -o40- or -o1200- while leaving the rest of the url intact? The urls could be anything, but I'd like to be able to find this exact pattern of -o20- and replace it with whatever number I want.

Thank you in advance.

2

There are 2 best solutions below

1
Sahil Gulati On BEST ANSWER

Hope this will work.

url = "/ShowForum-g1-i12105-o20-TripAdvisor_Support.html"
url = url.gsub!(/-o20-/, "something_to_replace") 
puts "url is : #{url}"

Output:

sh-4.3$ ruby main.rb                                                                                                                                                 
url is : /ShowForum-g1-i12105something_to_replaceTripAdvisor_Support.html 
2
Aleksei Matiushkin On
url[/(?<=-o)\d+(?=-)/] = ($&.to_i + 10).to_s

The snippet above will replace the number inplace with (itself + 10).

url = '/ShowForum-g1-i12105-o20-TripAdvisor_Support.html'

url[/(?<=-o)\d+(?=-)/] = ($&.to_i + 10).to_s
#⇒ "30"
url
#⇒ "/ShowForum-g1-i12105-o30-TripAdvisor_Support.html"
url[/(?<=-o)\d+(?=-)/] = ($&.to_i + 10).to_s
#⇒ "40"
url
#⇒ "/ShowForum-g1-i12105-o40-TripAdvisor_Support.html"

To replace with whatever number you want:

url[/(?<=-o)\d+(?=-)/] = "500"
url
#⇒ "/ShowForum-g1-i12105-o500-TripAdvisor_Support.html"

More info: String#[]=.