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.
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"))
                        (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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With