6

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".

2
  • stackoverflow.com/questions/3421044/… Commented Mar 5, 2014 at 16:57
  • 1
    The term "var" means something very specific in Clojure, and some-string isn't a var. It's just a function parameter. Commented Mar 5, 2014 at 16:58

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree, re-pattern is the easiest way to do this. It builds up a regex pattern from a string. To answer OP's question, you could do (re-find (re-pattern (str "(?i)" some-string)) "some sentence").
7

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)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.