Reputation: 603
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.
Upvotes: 9
Views: 2812
Reputation: 18005
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"))
Upvotes: 15
Reputation: 17771
(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)
Upvotes: 9