在rails中,尝试进行多次替换,但只有第一次替换

时间:2016-07-12 17:14:07

标签: regex ruby-on-rails-4 search replace substitution

我正在尝试对变量进行多次替换,其值为

https://api.mydomein.com/events/EVENTID/profiles?max=10&total=1&appid=1234f5bf9f36bc4a1dc8fce2&token=9997aa817ff66b96f3956835f17941e1&search=4001&func=na&parms=%7B%22browser%22%3Afalse%7D&settings=%7B%22setWait%22%3Afalse%7D&_=1468271558064

我试图以这种方式进行替换......

  object_desc_link = OBJECT_DESC_LINK_TEMPLATE.sub( %r{events\/([^\\])+}, "events/#{@event_id}" )
                         .sub( %r{appid=([^\&])+}, "appid=#{@app_id}" )
                         .sub( %r{token=([^\&])+}, "token=#{@token}" )
                         .sub( %r{search=([^\&])+}, "search=#{i}" )

但运行此语句后,值为

https://api.mydomein.com/events/EVENTID

出于某种原因,第一次替换是切断URL的最后部分。如何保留整个字符串并在我指定的位置进行替换?

1 个答案:

答案 0 :(得分:0)

你弄乱了你的正则表达式。应该是

%r{events/([^/])+}

你在那里\\。网址的路径部分没有反斜杠。

顺便说一句,为什么不使用正确的工具来完成这项工作?解析网址是一个已解决的问题。

s = 'https://api.mydomein.com/events/EVENTID/profiles?max=10&total=1&appid=1234f5bf9f36bc4a1dc8fce2&token=9997aa817ff66b96f3956835f17941e1&search=4001&func=na&parms=%7B%22browser%22%3Afalse%7D&settings=%7B%22setWait%22%3Afalse%7D&_=1468271558064'

require "addressable/uri"
uri = Addressable::URI.parse(s)
h = uri.query_values # => {"max"=>"10", "total"=>"1", "appid"=>"1234f5bf9f36bc4a1dc8fce2", "token"=>"9997aa817ff66b96f3956835f17941e1", "search"=>"4001", "func"=>"na", "parms"=>"{\"browser\":false}", "settings"=>"{\"setWait\":false}", "_"=>"1468271558064"}

h['appid'] = 'whatever'
uri.query_values = h
uri.path = uri.path.sub('EVENTID', '42')

uri.to_s # => "https://api.mydomein.com/events/42/profiles?_=1468271558064&appid=whatever&func=na&max=10&parms=%7B%22browser%22%3Afalse%7D&search=4001&settings=%7B%22setWait%22%3Afalse%7D&token=9997aa817ff66b96f3956835f17941e1&total=1"