在正则表达式中使用变量的正确方法是什么?例如:
(def var "/")
(split "foo/bar" #var)
Run Code Online (Sandbox Code Playgroud)
应该给
=> ["foo" "bar"]
Run Code Online (Sandbox Code Playgroud)
但它不会这样.那我该怎么做?非常感谢你提前.
nha*_*nha 13
你可以使用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)
Run Code Online (Sandbox Code Playgroud)
或者,使用线程最后一个宏:
(->> "/"
(re-pattern)
(clojure.string/split "foo/bar"))
Run Code Online (Sandbox Code Playgroud)
(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)
Run Code Online (Sandbox Code Playgroud)