rails 中 gsub 的正则表达式

Regex for gsub in rails

我有一个 rails 应用程序,我在其中使用 kaminari 进行分页。

不知何故 kaminari 对超链接使用了错误的 url。

现在我正在寻找一个简单的修复方法,它需要一些正则表达式和 gsubbing。

我有来自 kaminari 的 url:

"/bookings/hotels//Pune?arrival_date=....."

我想将这部分 - /hotels//Pune? 替换为 - /hotels?

可能有任何其他字符串代替 Pune(它可能会改变)。

我应该怎么做?

gsub("//浦那", "") 这里不需要 4 个正则表达式。

使用 match capture

捕获和替换
gsub(/hotels(\/\/\w+)\?/){|m| m.gsub(, '')}

str = "/bookings/hotels//Pune?arrival_date=....."
str.gsub(/hotels(\/\/\w+)\?/){|m| m.gsub(, '')}

#=> "/bookings/hotels?arrival_date=....."

我在处理 URL 时总是使用 URI library,它会为您做一些跑腿工作(尤其是在涉及查询字符串时)。

像这样的东西会适合你的情况,虽然也有可能首先得到正确的方法 URL!

require 'uri' # probably not necessary if you are using Rails

old_url  = "/bookings/hotels//Pune?arrival_date=blahblah"
uri      = URI(old_url)

# remove everything between the first double '//' and the end of the string
uri.path = uri.path.gsub(/\/\/.+\Z/, '')
# => "/bookings/hotels"

# output a new url using the new path but including the original query string
new_url  = uri.to_s
# =>  "/bookings/hotels?arrival_date=blahblah"