红宝石:解析字符串再嵌套数组的presentation成一个阵列? [英] Ruby: Parsing a string representation of nested arrays into an Array?
问题描述
比方说,我有字符串
"[1,2,[3,4,[5,6]],7]"
我将如何解析到数组
How would I parse that into the array
[1,2,[3,4,[5,6]],7]
嵌套结构和模式是在我的使用情况下,完全是任意的。
Nesting structures and patterns are completely arbitrary in my usage case.
我目前的临时解决方案涉及每一个时期后加空格和使用 YAML.load
,但我希望有可能的话一个更清洁的。
My current ad-hoc solution involves adding a space after every period and using YAML.load
, but I'd like to have a cleaner one if possible.
(一不需要外部库如果可能的话)
(One that does not require external libraries if possible)
推荐答案
这特殊的例子被正确解析使用 JSON
:
That particular example is being parsed correctly using JSON
:
s = "[1,2,[3,4,[5,6]],7]"
#=> "[1,2,[3,4,[5,6]],7]"
require 'json'
#=> true
JSON.parse s
#=> [1, 2, [3, 4, [5, 6]], 7]
如果不工作,你可以尝试运行通过 评估字符串
,但你必须确保没有实际红宝石code已经过去了,因为评估
可作为注入漏洞
If that doesn't work, you can try running the string through eval
, but you have to ensure that no actual ruby code has been passed, as eval
could be used as injection vulnerability.
编辑:这是一个简单的递归的,基于正则表达式解析器,没有验证,没有测试,不用于生产用途等:
Here is a simple recursive, regex based parser, no validation, not tested, not for production use etc:
def my_scan s
res = []
s.scan(/((\d+)|(\[(.+)\]))/) do |match|
if match[1]
res << match[1].to_i
elsif match[3]
res << my_scan(match[3])
end
end
res
end
s = "[1,2,[3,4,[5,6]],7]"
p my_scan(s).first #=> [1, 2, [3, 4, [5, 6]], 7]
这篇关于红宝石:解析字符串再嵌套数组的presentation成一个阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!