Danny Armstrong
Danny Armstrong

Reputation: 1310

How to parse this text into a tree?

I want to take text (sample below) and convert it into a nested data structure that can be walked:

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

Upvotes: 3

Views: 327

Answers (1)

mobyte
mobyte

Reputation: 3752

Is this the solution?

(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))))})

your string (supposed that "Gombas" is indented):

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

test

(parse s)
-> {"hierarchy" ({"dog" ({"Bailey" ()})}
                 {"cats" ({"Robert" ()}
                          {"Trev" ()}
                          {"Gombas" ()})})}

Upvotes: 4

Related Questions