0

我有以下单行字符串:

params = {"FieldStructure"=>"{\"Fields\":[{\"Title\":\"Company Name\",\"Type\":\"text\",\"ID\":\"Field6\"},{\"Title\":\"Email\",\"Type\":\"email\",\"ID\":\"Field5\"}]}", "Field6"=>"tettetette", "Field5"=>"test@tessss.pl", "EntryId"=>"25"}

格式化版:

params = {
  "FieldStructure"=>"
    {\"Fields\":[
      {\"Title\":\"Company Name\",\"Type\":\"text\",\"ID\":\"Field6\"},
      {\"Title\":\"Email\",\"Type\":\"email\",\"ID\":\"Field5\"}]}",
    "Field6"=>"tettetette", 
    "Field5"=>"test@tessss.pl", 
    "EntryId"=>"25"
}

我想收到:[["Company Name", "Field6"], ["Email", "Field5"]]

我尝试使用扫描方法但有一些问题:

>>  fields = params['FieldStructure'].scan(/Title\":\"(.+?)\".+ID\":\"(.+?)\"/)  
=> [["Company Name", "Field5"]]

如何做到这一点?

4

2 回答 2

1

非正则表达式解决方案:

require 'json'
params = {"FieldStructure"=>"{\"Fields\":[{\"Title\":\"Company Name\",\"Type\":\"text\",\"ID\":\"Field6\"},{\"Title\":\"Email\",\"Type\":\"email\",\"ID\":\"Field5\"}]}", "Field6"=>"tettetette", "Field5"=>"test@tessss.pl", "EntryId"=>"25"}

a = JSON.parse(params["FieldStructure"])
out = a["Fields"].map {|a| [a["Title"],a["ID"]]}
p out  # [["Company Name", "Field6"], ["Email", "Field5"]]
于 2013-04-11T12:05:29.973 回答
1

正确的方法是:

params['FieldStructure'].scan(/Title\":\"(.+?)\".+?ID\":\"(.+?)\"/)  

您在 ID 之前的 .+ 是贪婪的,这意味着它会消耗尽可能多的字符,直到找到下一个 ID。这 ?最终使它变得不那么贪婪。

于 2013-04-11T12:01:22.413 回答