Search code examples
clojure

How to split string in clojure on number and convert it to map


I have a string school_name_1_class_2_city_name_3 want to split it to {school_name: 1, class:2, city_name: 3} in clojure I tried this code which didn't work

(def s "key_name_1_key_name_2")
(->> s
     (re-seq #"(\w+)_(\d+)_")
     (map (fn [[_ k v]] [(keyword k) (Integer/parseInt v)]))
     (into {}))

Solution

  • You are looking for the ungreedy version of regex.

    Try using #"(\w+?)_(\d+)_?" instead.

    user=> (->> s (re-seq #"(\w+?)_(\d+)_?"))
    (["key_name_1_" "key_name" "1"] ["key_name_2" "key_name" "2"])