Ruby:将嵌套数组的字符串表示解析为数组? [英] Ruby: Parsing a string representation of nested arrays into an Array?

查看:46
本文介绍了Ruby:将嵌套数组的字符串表示解析为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有字符串

"[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]

如果这不起作用,您可以尝试通过 eval,但您必须确保没有传递实际的 ruby​​ 代码,因为 eval 可能被用作注入漏洞.

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]

这篇关于Ruby:将嵌套数组的字符串表示解析为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆