9

What is the correct way to use variables in a regular expression? E.g.:

(def var "/")
(split "foo/bar" #var)

should give

=> ["foo" "bar"]

But it doesn't work this way. So how do I do that? Thank you very much in advance.

2 Answers 2

15

You can use re-pattern :

(def var "/")                ; variable containing a string
(def my-re (re-pattern var)) ; variable string to regex

(clojure.string/split "foo/bar" my-re)

Or, using a thread-last macro :

(->> "/"
     (re-pattern)
     (clojure.string/split "foo/bar"))
Sign up to request clarification or add additional context in comments.

Comments

9
(def my-re (java.util.regex.Pattern/compile "/")) ; to turn a string into a regex
;; or just
(def my-re #"/") ; if the regex can be a literal

(clojure.string/split "foo/bar" my-re)

2 Comments

Wow, that was quick! Thanks a lot!
(re-pattern "/") will do as well, slightly more concise than (java.util.regex.Pattern/compile "/")

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.