dirtyvagabond
dirtyvagabond

Reputation: 1921

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?

Upvotes: 12

Views: 2863

Answers (4)

willscripted
willscripted

Reputation: 1456

To match a string verbatim, ignoring special characters:

(defn to-regex [some-string]
  (re-pattern (java.util.regex.Pattern/quote some-string)))

Then ... will only match ..., not aaa or any other three letter combination.

Upvotes: 0

j-g-faustus
j-g-faustus

Reputation: 9009

There is a function for it: re-pattern

user=> (re-pattern "\\d+")
#"\d+"

Upvotes: 30

kotarak
kotarak

Reputation: 17309

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.

Upvotes: 8

Sean
Sean

Reputation: 29790

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

user=> (. java.util.regex.Pattern compile "mystr")
#"mystr"

Upvotes: 0

Related Questions