为什么它必须是正则表达式对象?
在这里,我们可以先使用一个 Hash 对象,然后再去搜索它。
mh = {"url":"http://www.netcharles.com/orwell/essays.htm","domain":"netcharles.com","title":"Orwell Essays & Journalism Section - Charles' George Orwell Links","tags":["orwell","writing","literature","journalism","essays","politics","essay","reference","language","toread"],"index":2931,"time_created":1345419323,"num_saves":24}
其输出将是
=> {:url=>"http://www.netcharles.com/orwell/essays.htm", :domain=>"netcharles.com", :title=>"Orwell Essays & Journalism Section - Charles' George Orwell Links", :tags=>["orwell", "writing", "literature", "journalism", "essays", "politics", "essay", "reference", "language", "toread"], :index=>2931, :time_created=>1345419323, :num_saves=>24}
并不是说我想避免使用正则表达式,但是您不认为在获得要进一步搜索的数据之前一次更容易地采取一步吗?只是MHO。
mh.values_at(:url, :title, :tags)
输出:
["http://www.netcharles.com/orwell/essays.htm", "Orwell Essays & Journalism Section - Charles' George Orwell Links", ["orwell", "writing", "literature", "journalism", "essays", "politics", "essay", "reference", "language", "toread"]]
采用 FrankieTheKneeman 给您的模式:
pattern = /"(url|title|tags)":"((\\"|[^"])*)"/i
我们可以通过将 mh 哈希转换为 json 对象来搜索它。
/#{pattern}/.match(mh.to_json)
输出:
=> #<MatchData "\"url\":\"http://www.netcharles.com/orwell/essays.htm\"" 1:"url" 2:"http://www.netcharles.com/orwell/essays.htm" 3:"m">
当然,这一切都是在 Ruby 中完成的,这不是您拥有的标签,但我希望与之相关。
但是哎呀!看起来我们不能用这种模式一次完成所有三个,所以我一次只做一个。
pattern = /"(title)":"((\\"|[^"])*)"/i
/#{pattern}/.match(mh.to_json)
#<MatchData "\"title\":\"Orwell Essays & Journalism Section - Charles' George Orwell Links\"" 1:"title" 2:"Orwell Essays & Journalism Section - Charles' George Orwell Links" 3:"s">
pattern = /"(tags)":"((\\"|[^"])*)"/i
/#{pattern}/.match(mh.to_json)
=> nil
对不起最后一个。它必须以不同的方式处理。