我想将以下字符串转换为数组/嵌套数组:

str = "[[this, is],[a, nested],[array]]"

newarray = # this is what I need help with!

newarray.inspect  # => [['this','is'],['a','nested'],['array']]
有帮助吗?

解决方案

通过 YAML,您将得到您想要的。

但是你的绳子有点问题。YAML 要求逗号后面有一个空格。所以我们需要这个

str = "[[this, is], [a, nested], [array]]"

代码:

require 'yaml'
str = "[[this, is],[a, nested],[array]]"
### transform your string in a valid YAML-String
str.gsub!(/(\,)(\S)/, "\\1 \\2")
YAML::load(str)
# => [["this", "is"], ["a", "nested"], ["array"]]

其他提示

为了笑:

 ary = eval("[[this, is],[a, nested],[array]]".gsub(/(\w+?)/, "'\\1'") )
 => [["this", "is"], ["a", "nested"], ["array"]]

免责声明:你绝对不应该这样做 eval 是一个糟糕的主意,但它速度很快,并且具有在嵌套数组无效时抛出异常的有用副作用

您也可以将其视为近似 JSON。如果字符串确实只是字母,就像您的示例一样,那么这将起作用:

JSON.parse(yourarray.gsub(/([a-z]+)/,'"\1"'))

如果它们可以有任意字符(除 [ ] , ),您需要更多:

JSON.parse("[[this, is],[a, nested],[array]]".gsub(/, /,",").gsub(/([^\[\]\,]+)/,'"\1"'))

看起来像是一个基本的解析任务。通常,您要采用的方法是使用以下通用算法创建递归函数

base case (input doesn't begin with '[') return the input
recursive case:
    split the input on ',' (you will need to find commas only at this level)
    for each sub string call this method again with the sub string
    return array containing the results from this recursive method

这里唯一有点棘手的部分是将输入拆分为单个“,”。您可以为此编写一个单独的函数,该函数将扫描字符串并保留迄今为止看到的开括号和闭括号的计数。然后仅当计数等于零时才用逗号分割。

创建一个递归函数,它接受字符串和整数偏移量,并“读出”一个数组。也就是说,让它返回一个数组或字符串(它已读取)以及指向该数组后面的整数偏移量。例如:

s = "[[this, is],[a, nested],[array]]"

yourFunc(s, 1) # returns ['this', 'is'] and 11.
yourFunc(s, 2) # returns 'this' and 6.

然后您可以使用另一个提供 0 偏移量的函数来调用它,并确保最终偏移量是字符串的长度。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top