简体   繁体   中英

Having trouble doing a search and replace in Ruby

I'm using Rails 4.2.3 and trying to do a regular expression search and replace. If my variable starts out like so …

url = “http://results.mydomain.com/json/search?eventId=974&subeventId=2320&callback=jQuery18305053194007595733_1464633458265&sEcho=3&iColumns=13&sColumns=&iDisplayStart=1&iDisplayLength=100&mDataProp_0=“

and then I run that through

display_start = url.match(/iDisplayStart=(\d+)/).captures[0] 
display_start = display_start.to_i + 1000
url = url.gsub(/iDisplayStart=(\d+)/) { display_start }     

The result is

http://results.mydomain.com/json/search?eventId=974&subeventId=2320&callback=jQuery18305053194007595733_1464633458265&sEcho=3&iColumns=13&sColumns=&1001&iDisplayLength=100&mDataProp_0=

But what I want is to simply replace the “iDisplayStart” parameter with my new value, so I would like the result to be

http://results.mydomain.com/json/search?eventId=974&subeventId=2320&callback=jQuery18305053194007595733_1464633458265&sEcho=3&iColumns=13&sColumns=&1001&iDisplayStart=1001&iDisplayLength=100&mDataProp_0=

How do I do this?

You can achieve what you want with

url = "http://results.mydomain.com/json/search?eventId=974&subeventId=2320&callback=jQuery18305053194007595733_1464633458265&sEcho=3&iColumns=13&sColumns=&iDisplayStart=1&iDisplayLength=100&mDataProp_0="
display_start = url.sub(/(?<=iDisplayStart=)\d+/) {|m| m.to_i+1000}
puts  display_start

See the IDEONE demo

Since you replace 1 substring, you do not need gsub , a sub will do.

The block takes the whole match (that is, 1 or more digits that are located before iDisplayStart ), m , and converts to an int value that we add 1000 to inside the block.

Another way is to use your regex (or add \\b for a safer match) and access the captured vaalue with Regexp.last_match[1] inside the block:

url = "http://results.mydomain.com/json/search?eventId=974&subeventId=2320&callback=jQuery18305053194007595733_1464633458265&sEcho=3&iColumns=13&sColumns=&iDisplayStart=1&iDisplayLength=100&mDataProp_0="
display_start = url.sub(/\biDisplayStart=(\d+)/) {|m| "iDisplayStart=#{Regexp.last_match[1].to_i+1000}" }
puts  display_start

See this IDEONE demo

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