Escaping brackets in Clojure

Viewed 5038

If I try this

(import java.util.regex.Pattern)
(Pattern/compile ")!@#$%^&*()")

or this

(def p #")!@#$%^&*()")

I have Clojure complaining that there is an unmatched / unclosed ). Why are brackets evaluated within this simple string? How to escape them? Thanks

EDIT: While escaping works in the clojure-specific syntax (#""), it doesn't work with the Pattern/compile syntax that I do need because I have to compile the regex patter dynamically from a string.

I've tried with re-pattern, but I can't escape properly for some reason:

(re-pattern "\)!@#$%^&*\(\)")
    java.lang.Exception: Unsupported escape character: \)
    java.lang.Exception: Unable to resolve symbol: ! in this context (NO_SOURCE_FILE:0)
    java.lang.Exception: No dispatch macro for: $
    java.lang.Exception: Unable to resolve symbol: % in this context (NO_SOURCE_FILE:0)
    java.lang.IllegalArgumentException: Metadata can only be applied to IMetas

EDIT 2 This little function may help:

(defn escape-all [x]
    (str "\\" (reduce #(str  %1 "\\" %2) x)))
3 Answers
Related