2011-05-16 165 views
1

我有這個字符串: 「asdasda = asdaskdmasd & asmda = asdasmda & ACK =成功& asdmas = asdakmsd & asmda = adasda」紅寶石字符串分割問題

我想要的ACK之間後得到的值&象徵,ACK和&符號之間的值可以改變...

感謝

我想在紅寶石的解決方案。

回答

5
require "cgi" 

query_string = "asdasda=asdaskdmasd&asmda=asdasmda&ACK=Success&asmda=asdakmsd" 
parsed_query_string = CGI.parse(query_string) 
#=> { "asdasda" => ["asdaskdmasd"], 
#  "asmda" => ["asdasmda", "asdakmsd"], 
#  "ACK" => ["Success"] } 

parsed_query_string["ACK"].first 
#=> "Success" 

如果你也想(用URL的其餘部分特別合)重建查詢字符串,我會建議尋找到了addressable寶石。

require "addressable/uri" 

# Note the leading '?' 
query_string = "?asdasda=asdaskdmasd&asmda=asdasmda&ACK=Success&asmda=asdakmsd" 
parsed_uri = Addressable::URI.parse(query_string) 
parsed_uri.query_values["ACK"] 
#=> "Success" 

parsed_uri.query_values = parsed_uri.query_values.merge("ACK" => "Changed") 
parsed_uri.to_s 
#=> "?ACK=Changed&asdasda=asdaskdmasd&asmda=asdakmsd" 
# Note how the order has changed and the duplicate key has been removed due to 
# Addressable's built-in normalisation. 
+0

+1用於獲取ACK沒有破解。 – 2011-05-16 22:55:53

0
s = "asdasda=asdaskdmasd&asmda=asdasmda&ACK=Success&asdmas=asdakmsd&asmda=adasda" 
m = s.match /.*ACK=(.*?)&/ 
puts m[1] 

,只是爲了好玩無正則表達式:

Hash[s.split("&").map{|p| p.split("=")}]["ACK"] 
0
"asdasda=asdaskdmasd&asmda=asdasmda&ACK=Success&asdmas=asdakmsd&asmda=adasda"[/ACK=([^&]*)&/] 
$1 # => 'Success' 
0

一個快速的方法:

s = "asdasda=asdaskdmasd&asmda=asdasmda&ACK=Success&asdmas=asdakmsd&asmda=adasda" 
s.gsub(/ACK[=\w]+&/,"ACK[changedValue]&") 
    #=> asdasda=asdaskdmasd&asmda=asdasmda&ACK[changedValue]&asdmas=asdakmsd&asmda=adasda