animalcroc
animalcroc

Reputation: 293

dynamic regex argument in re-find function in clojure

I'm using the re-find function in clojure, and have something like this:

(defn some-function []
(re-find #"(?i)blah" "some sentence"))

What I would like is to make the "blah" dynamic, so I substituted a var for blah like this, but it doesn't work:

(defn some-function2 [some-string]
(re-find #(str "(?i)" some-string) "some sentence"))

I'm surprised this doesn't work since LISP is supposed to "treat code like data".

Upvotes: 6

Views: 3235

Answers (2)

joelittlejohn
joelittlejohn

Reputation: 11832

To create a pattern from a string value in Clojure you can use re-pattern:

(re-pattern (str "(?i)" some-string))

One thing you don't mention is whether some-string is expected to contain a valid regex or whether it's an arbitrary string value. If some-string is an arbitrary string value (that you want to match exactly) you should quote it before using it to build your regex:

(re-pattern (str "(?i)" (java.util.regex.Pattern/quote some-string)))

Upvotes: 7

DanLebrero
DanLebrero

Reputation: 8593

Use the function re-pattern. #"" is just a reader macro (aka. syntactic sugar for creating regex)

#(str "(?i)" some-string) is reader macro to create an anonymous functions.

Upvotes: 12

Related Questions