Created
August 15, 2013 15:58
-
-
Save glorphindale/6242019 to your computer and use it in GitHub Desktop.
Парсим простой человеколюбивый файл конфигурации.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(require '[clojure.string :as cs]) | |
(def conf | |
"key1=val1 | |
key2 = val2 | |
key3 = \\ | |
val3 | |
key\\ | |
4=val4 | |
key5=\\ | |
val5 | |
key6=\\ | |
val\\ | |
6 | |
keyemp= | |
ke\\ | |
y\\ | |
7=\\ | |
va\\ | |
l7 | |
") | |
(defn parse-conf [text] | |
; [^\\]\n is a separator between two key-value pairs | |
(let [p (cs/replace text #"([^\\])\n" "$1\n\n") | |
sp (cs/split p #"\n\n")] | |
(->> sp | |
(map #(cs/replace % #"[\\|\n|\ ]" "")) | |
(map cs/trim) | |
(filter #(not (cs/blank? %))) | |
(map #(cs/split % #"=")) | |
(map #(if (= (count %) 1) [(first %) nil] %)) ; Handle empty value | |
(flatten) | |
(apply hash-map)))) | |
(println (parse-conf conf)) | |
> {keyemp nil, key1 val1, key2 val2, key3 val3, key4 val4, key5 val5, key6 val6, key7 val7} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment