9

次の文字列を配列/ネストされた配列に変換したいと思います。

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

newarray = # this is what I need help with!

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

5 に答える 5

11

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"]]
于 2008-09-02T22:39:27.503 に答える
4

ほぼ JSON として扱うこともできます。あなたの例のように、文字列が実際に文字だけである場合、これは機能します:

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

任意の文字 ( [ ] 、 以外) を使用できる場合は、もう少し必要になります。

JSON.parse("[[this, is],[a, nested],[array]]".gsub(/, /,",").gsub(/([^\[\]\,]+)/,'"\1"'))
于 2008-09-18T02:55:35.167 に答える
3

笑いのために:

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

免責事項:ひどい考えのようにこれを行うべきではありませんがeval、高速であり、ネストされた配列が有効でない場合に例外をスローするという便利な副作用があります

于 2008-09-01T22:06:44.767 に答える
0

基本的な解析タスクのように見えます。一般的に、採用したいアプローチは、次の一般的なアルゴリズムを使用して再帰関数を作成することです。

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

ここでの唯一の巧妙なトリッキーな部分は、入力を単一の「、」に分割することです。このために、文字列をスキャンしてオープンブラケット(これまでに見られたクローズドブラケット)のカウントを保持する別の関数を作成できます。次に、カウントがゼロに等しい場合にのみコンマで分割します。

于 2008-09-01T21:44:01.620 に答える
0

文字列と整数オフセットを取得し、配列を「読み取る」再帰関数を作成します。つまり、配列または文字列(読み取ったもの)と、配列の後ろを指す整数オフセットを返すようにします。例えば:

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

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

次に、オフセット0を提供する別の関数を使用して呼び出すことができ、最後のオフセットが文字列の長さであることを確認します。

于 2008-09-01T21:47:52.407 に答える