在ruby中,我尝试用新数字替换以下网址的粗体部分:
/ ShowForum-G1-i12105-的 O20 -TripAdvisor_Support.html
我如何定位和替换 -o20 - 使用-o30-或-o40-或-o1200-而留下其余的URL 完整?网址可以是任何内容,但我希望能够找到-o20-的这种确切模式,并将其替换为我想要的任何数字。
提前谢谢你。
答案 0 :(得分: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
答案 1 :(得分: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#[]=
。