3

我想获取文本(下面的示例)并将其转换为可以遍历的嵌套数据结构:

Arbirarchy !
  dog, my friend
    Bailey the Great
  cats, my enemies
    Robert the Terrible
    Trev the Diner
    Gombas the Tasty
      Lenny Lion
  Alligators
    Sadly I have none
4

1 回答 1

4

这是解决方案吗?

(defn parse [s]
  {(re-find #"(?m)^.+" s)
   (map parse (map #(str/replace % #"(?m)^\s{2}" "")
                   (map first (re-seq #"(?m)(^\s{2}.+(\n\s{4}.+$)*)" s))))})

你的字符串(假设“Gombas”是缩进的):

(def s "hierarchy\n  dog\n    Bailey\n  cats\n    Robert\n    Trev\n    Gombas")

测试

(parse s)
-> {"hierarchy" ({"dog" ({"Bailey" ()})}
                 {"cats" ({"Robert" ()}
                          {"Trev" ()}
                          {"Gombas" ()})})}
于 2012-11-15T08:30:59.247 回答