2011-04-11 19 views
-1

我有以下简单的JSON字符串:简单的Ruby的正则表达式JSON字符串

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

,我想提取下面的“排除”在阵列中的每个数字。换句话说,我期望我的第0场比赛是全部数据,我的第一场比赛是4号,我的第5场比赛,等等。非常感谢。

+3

你JSON.parse(串)可以吗? – christianblais 2011-04-11 18:27:46

+11

我对两件事感到困惑:** 1。**当JSON的全部存在理由是每种语言都已经为它编写了解析器时,为什么要用正则表达式扫描JSON? ** 2。**这不是JSON,它几乎是Ruby,它看起来像'Kernel#p'的输出。 – DigitalRoss 2011-04-11 18:29:14

回答

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] 
+0

谢谢道格拉斯! – mbm 2011-04-11 18:45:47

+1

很高兴帮助。正如其他人所说,查看一个JSON解析器。当然,您可能会有一些我们不知道的性能方面的考虑因素。 – 2011-04-11 19:15:34

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 # => [] 
0

正如指出的DigitalRoss ,你的字符串不包含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