views:

138

answers:

3

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?

A: 

I may be misunderstanding the question, but doesn't this do what you want?

user=> (. java.util.regex.Pattern compile "mystr")
#"mystr"
Sean
yes it does exactly what i want. but you have to admit, not as pretty as j-g-faustus's (re-pattern "mystr")
dirtyvagabond
No, indeed not.
Sean
+13  A: 

There is a function for it: re-pattern

user=> (re-pattern "\\d+")
#"\d+"
j-g-faustus
+3  A: 

To explain a bit more:

#"" is a reader macro. It is resolved at read time by the reader. So there is no way to create a macro which expands into a reader macro, because the read phase is long gone. A macro returns the actual data structure representing the expanded code, not a string which is parsed again like eg. #define works in C.

j-g-faustus' answer is the Right Way(tm) to go.

kotarak
Thanks kotarak. I should have realized why the reader life cycle prevents me from doing what I was trying to do. Thanks!
dirtyvagabond