用于JSON字符串的简单Ruby Regex

时间:2011-04-11 18:15:57

标签: ruby regex json

我有以下简单的JSON字符串:

{\"exclude\"=>[4, 5, 6, 10], \"include\"=>[]}

我想在“排除”之后提取数组中的每个数字。换句话说,我希望我的第0场比赛是所有数字,我的第一场比赛是4,我的第二场比赛是5,依此类推。非常感谢。

3 个答案:

答案 0 :(得分:1)

也许不像你希望的那样整齐的正则表达式:

s = '{\"exclude\"=>[4, 5, 6, 10], \"include\"=>[]}'

all_numbers = s[/\[[\d,\s]+\]/]
# => "[4, 5, 6, 10]"

all_numbers.scan(/\d+/).map { |m| m.to_i }
# => [4, 5, 6, 10]

# Depends how much you trust the regex that grabs the result for all_numbers.
eval(all_numbers)
# => [4, 5, 6, 10]

# As a one-liner.
s[/\[[\d,\s]+\]/].scan(/\d+/).map { |m| m.to_i } # => [4, 5, 6, 10]

答案 1 :(得分:0)

如果我真的必须在这里使用正则表达式,我会做这样的事情:

string = "{\"exclude\"=>[4, 5, 6, 10], \"include\"=>[]}"

exclude, include = string.scan(/(\[[\d,\s]{0,}\])/).map {|match| eval match.first}

exclude # => [4, 5, 6, 10]
include # => []

答案 2 :(得分:0)

正如DigitalRoss所指出的,你的String不包含JSON,但显然是纯Ruby代码。

您可以轻松评估并简单地访问它:

lStr = "{\"exclude\"=>[4, 5, 6, 10], \"include\"=>[]}"

# Evaluate the string: you get a map
lMap = eval(lStr)
# => {"exclude"=>[4, 5, 6, 10], "include"=>[]}

# Read the properties
lMap['exclude']
# => [4, 5, 6, 10]
lMap['include']
# => []
lMap['exclude'][2]
# => 6