Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: How to use variables in regular expressions?

Tags:

clojure

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.

like image 798
A Friedrich Avatar asked Jan 07 '12 12:01

A Friedrich


2 Answers

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"))
like image 195
nha Avatar answered Sep 28 '22 07:09

nha


(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)
like image 22
Joost Diepenmaat Avatar answered Sep 28 '22 08:09

Joost Diepenmaat