简体   繁体   English

用于gsub的正则表达式

[英]Regex for gsub in rails

I have a rails application where I am using kaminari for pagination. 我在使用kaminari进行分页的Rails应用程序中。

Somehow kaminari is using wrong url for hyperlinks. kaminari不知何故为超链接使用了错误的URL。

Right now I am looking for an easy fix which requires some regex & gsubbing. 现在,我正在寻找一个简单的修复程序,需要一些正则表达式和gsubbing。

I have this url from kaminari: 我有来自kaminari的网址:

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

I want to replace this part - /hotels//Pune? 我要替换这部分- /hotels//Pune? with this - /hotels? 这个- /hotels?

There could be any other string in place of Pune (it might change). 可以使用其他任何字符串代替Pune (它可能会更改)。

How should I do this ? 我该怎么办?

Capture and replace using match capture 使用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=....."

I always use the URI library when messing around with URLs, it does some of the legwork for you (especially if query strings are involved). 在处理URL时,我总是使用URI库 ,它为您完成了一些繁琐的工作(特别是如果涉及查询字符串)。

Something like this would suit your situation, although there's probably a way to get the right URL in the first place too! 这样的事情将适合您的情况,尽管也可能有一种方法也可以首先获取正确的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