Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a Clojure macro to create a regular expression from a String?

I'm creating a convenience macro. Part of the convenience is that a regular expression can be specified with just a String, rather than the #"re" notation.

The one part I can't figure out is how to get the macro to take the String and rewrite it as a Clojure regex (e.g., produce the #"re" notation). I think it's a syntax / escaping problem.

My first naive attempt (pretending I only want the String-to-regex part):

(defmacro mymac [mystr] `#~mystr)

Is it even possible to do what I'm trying to do? Or, is there an actual function to take a String and produce a regex, instead of using the # reader macro?

Or should I just drop into Java and use java.util.regex.Pattern?

like image 744
dirtyvagabond Avatar asked Aug 06 '10 04:08

dirtyvagabond


1 Answers

There is a function for it: re-pattern

user=> (re-pattern "\\d+")
#"\d+"
like image 70
j-g-faustus Avatar answered Oct 07 '22 02:10

j-g-faustus