12

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?

4 Answers 4

30

There is a function for it: re-pattern

user=> (re-pattern "\\d+")
#"\d+"
Sign up to request clarification or add additional context in comments.

Comments

8

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.

1 Comment

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

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

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

1 Comment

yes it does exactly what i want. but you have to admit, not as pretty as j-g-faustus's (re-pattern "mystr")
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.