2008-09-01 78 views

回答

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"]] 
+0

非常感謝您的支持!試圖弄清楚這一點我正要瘋了。 :) – CalebHC 2010-06-03 04:59:17

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 

唯一slighlty棘手的部分是在這裏分裂在單一的輸入「」。您可以爲此編寫一個單獨的函數來掃描字符串並保留openbrackets的數量 - 迄今爲止看到的closedbrakets。然後只在計數等於零時以逗號分割。

0

建立一個遞歸函數,它接受字符串和整數偏移量,並「讀出」一個數組。也就是說,讓它返回一個數組或字符串(它已經讀取)和一個指向數組後的整數偏移量。例如:

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

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

然後你就可以與提供的0偏移,並確保精偏移是字符串的長度,另一個函數調用它。

3

一笑道:

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

免責聲明:你絕對不應該這樣做,因爲eval是一個可怕的想法,但它是速度快,拋出一個異常,如果你嵌套數組AREN的有用的副作用有效

3

你也可以把它當作幾乎JSON。如果字符串真的是字母,就像在你的榜樣,那麼這將工作:

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

如果他們能有任意字符([],其他),你需要多一點:

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