Reputation: 8338
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.
Upvotes: 1
Views: 154
Reputation: 121000
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#[]=
.
Upvotes: 1
Reputation: 15141
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
Upvotes: 1