Hamza Yerlikaya
Hamza Yerlikaya

Reputation: 49329

Clojure Parse String

I have the following string

layout: default
title: Envy Labs

What i am trying to do is create map from it

layout->default 
title->"envy labs"

Is this possible to do using sequence functions or do i have to loop through each line?

Trying to get a regex to work with and failing using.


(apply hash-map (re-split #": " meta-info))

Upvotes: 4

Views: 2632

Answers (3)

Timothy Pratley
Timothy Pratley

Reputation: 10662

I'd recommend using clojure-contrib/duck-streams/read-lines to process the lines then split the fields from there. I find this method is usually more robust to errors in the file.

Upvotes: 1

Jim Downing
Jim Downing

Reputation: 1491

The _ is a variable name used to indicate that you don't care about the value of the variable (in this case, the whole matched string).

Upvotes: 3

Brian Carper
Brian Carper

Reputation: 72926

user> (let [x "layout: default\ntitle: Envy Labs"]
        (reduce (fn [h [_ k v]] (assoc h k v))
                {}
                (re-seq #"([^:]+): (.+)(\n|$)" x)))
{"title" "Envy Labs", "layout" "default"}

Upvotes: 4

Related Questions