1

在 ruby​​ 中,我正在尝试用新数字替换以下网址的粗体部分:

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

我如何将 -o20- 定位并替换为-o30- 或 -o40- 或 -o1200- ,同时保持 URL 的其余部分完好无损?url 可以是任何东西,但我希望能够找到这个确切的 -o20- 模式并将其替换为我想要的任何数字。

先感谢您。

4

2 回答 2

1

希望这会奏效。

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

输出:

sh-4.3$ ruby main.rb                                                                                                                                                 
url is : /ShowForum-g1-i12105something_to_replaceTripAdvisor_Support.html 
于 2017-02-22T05:44:58.160 回答
1
url[/(?<=-o)\d+(?=-)/] = ($&.to_i + 10).to_s

上面的代码片段将用(本身 + 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"

要替换为您想要的任何数字:

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

更多信息:String#[]=

于 2017-02-22T06:28:58.053 回答