简体   繁体   中英

Regex for gsub in rails

I have a rails application where I am using kaminari for pagination.

Somehow kaminari is using wrong url for hyperlinks.

Right now I am looking for an easy fix which requires some regex & gsubbing.

I have this url from kaminari:

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

I want to replace this part - /hotels//Pune? with this - /hotels?

There could be any other string in place of Pune (it might change).

How should I do this ?

Capture and replace using 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).

Something like this would suit your situation, although there's probably a way to get the right URL in the first place too!

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个正则表达式。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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