Sliding brackets in Clojure

If I try this one

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

or

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

I have a Clojure complaining that there is an unrivaled / open-ended ). Why are parentheses evaluated inside this simple string? How to avoid them? Thanks

EDIT . While escaping works in the syntax of clojure ( #""), it does not work with the syntax Pattern/compileI need, because I need to compile regex patter dynamically from a string.

I tried with re-pattern, but for some reason I cannot escape properly:

(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 small feature may help:

(defn escape-all [x]
    (str "\\" (reduce #(str  %1 "\\" %2) x)))
+5
source share
3 answers

I earned by doubling everything. Oh, the joys of double escape.

=> (re-pattern "\\)\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)")
=> #"\)\!\@\#\$\%\^\&\*\(\)"

=> (re-find (re-pattern "\\)\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)")
            ")!@#$%^&*()")
=> ")!@#$%^&*()"

str-to-pattern ( , ), , , re-pattern .

:
, - . , . "Smap" , , " " " ", " " smap " ", vals of smap. smap {\( "\\(", \) "\\)" ...}.

(def regex-char-esc-smap
  (let [esc-chars "()*&^%$#!"]
    (zipmap esc-chars
            (map #(str "\\" %) esc-chars))))

- . smap , . , ->> , .

(defn str-to-pattern
  [string]
  (->> string
       (replace regex-char-esc-smap)
       (reduce str)
       re-pattern))
+10

, (.. clojure)?

regexps , . , , .

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

[update] ah, , , , Omri.

+3

Java, Clojure \Q, \E, . - :

(re-find #"\Q)!@#$%^&*()\E" ")!@#$%^&*()")

(re-pattern), :

(re-find (re-pattern "\\Q)!@#$%^&*()\\E") ")!@#$%^&*()")

If you are building a regular expression from a string whose contents you do not know, you can use the method quotein java.util.regex.Pattern:

(re-find (re-pattern (java.util.regex.Pattern/quote some-str)) some-other-str)

Here is an example of this from my REPL:

user> (def the-string ")!@#$%^&*()")
#'user/the-string
user> (re-find (re-pattern (java.util.regex.Pattern/quote the-string)) the-string)
")!@#$%^&*()"
+1
source

All Articles