繁体   English   中英

用于gsub的正则表达式

[英]Regex for gsub in rails

我在使用kaminari进行分页的Rails应用程序中。

kaminari不知何故为超链接使用了错误的URL。

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

我有来自kaminari的网址:

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

我要替换这部分- /hotels//Pune? 这个- /hotels?

可以使用其他任何字符串代替Pune (它可能会更改)。

我该怎么办?

使用match capture来捕获和替换

gsub(/hotels(\/\/\w+)\?/){|m| m.gsub($1, '')}

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

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

在处理URL时,我总是使用URI库 ,它为您完成了一些繁琐的工作(特别是如果涉及查询字符串)。

这样的事情将适合您的情况,尽管也可能有一种方法也可以首先获取正确的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"

gsub(“ // Pune”,“”)此处不需要4个正则表达式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM