rubyregexrubular

replace specific text in ruby using regex


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.


Solution

  • 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