当前位置:首页> 正文

如何将带括号的 Ruby 字符串转换为数组?

如何将带括号的 Ruby 字符串转换为数组?

How do I convert a Ruby string with brackets to an array?

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

1
2
3
4
5
str ="[[this, is],[a, nested],[array]]"

newarray = # this is what I need help with!

newarray.inspect  # = [['this','is'],['a','nested'],['array']]

你会得到你想要的 YAML。

但是你的字符串有点问题。 YAML 期望逗号后面有一个空格。所以我们需要这个

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

代码:

1
2
3
4
5
6
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"]]

您也可以将其视为几乎 JSON。如果字符串真的只是字母,就像在你的例子中一样,那么这将起作用:

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

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

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

笑一笑:

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

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


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

1
2
3
4
s ="[[this, is],[a, nested],[array]]"

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

然后你可以用另一个提供偏移量0的函数调用它,并确保完成偏移量是字符串的长度。


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

1
2
3
4
5
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

这里唯一有点棘手的部分是将输入拆分为单个","。您可以为此编写一个单独的函数,该函数将扫描字符串并保持对 openbrackets 的计数 - 到目前为止看到的 closedbrakets。然后仅在计数为零时以逗号分隔。


展开全文阅读

相关内容