Rohit
Rohit

Reputation: 79

How do I pass a value to re-matches as a regular expression instead of a string constant

I am trying to pass a value into clojure's re-matches function for a regular expression like so

(defn extract-val
[k data]
  (let [r (format ".*\"%s\":\"(.*?)\".*" k)
        v ((last (re-matches #(str r) data)))]
 v))

Calling this function as (extract-val "event" "{\"event\":\"data\"}")

throws a class cast exception with a message that says cannot be cast to java.util.regex.Pattern clojure.core/re-matcher

Is there any way to do this or do i have to use the regex.Pattern directly

Upvotes: 2

Views: 306

Answers (1)

Lee
Lee

Reputation: 144196

#(str r) creates an anonymous function of 0 arguments which evaluates str r when called. You can create a pattern with re-pattern:

(last (re-matches (re-pattern r) data)

You should use a parser rather than regex if you're processing JSON however.

Upvotes: 3

Related Questions