红宝石串分裂问题

时间:2011-05-16 12:15:04

标签: ruby split

我有这个字符串: “asdasda = asdaskdmasd&安培; asmda = asdasmda&安培; ACK =成功&安培; asdmas = asdakmsd&安培; asmda = adasda”

我希望获得ACK和&之间的值。符号,ACK和&之间的值。符号可以改变......

感谢

我想要红宝石的解决方案。

4 个答案:

答案 0 :(得分: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 gem。

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.

答案 1 :(得分: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"]

答案 2 :(得分:0)

"asdasda=asdaskdmasd&asmda=asdasmda&ACK=Success&asdmas=asdakmsd&asmda=adasda"[/ACK=([^&]*)&/]
$1 # => 'Success'

答案 3 :(得分: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