3

When I am in Clojure, I can use (re-pattern (java.util.regex.Pattern/quote foo)) to exactly match the pattern string with another string. How can I do a similar thing in ClojureScript?

Edit: I also found this - Replicate the functionality of Java's "Pattern.quote" in a JavaScript RegExp

Community
  • 1
  • 1
Shantanu Kumar
  • 1,240
  • 1
  • 12
  • 14

2 Answers2

3

There is no built-in Clojure or Javascript function for this.

This clojure function should escape special regexp characters in a string:

(defn re-quote [s]
  (let [special (set ".?*+^$[]\\(){}|")
        escfn #(if (special %) (str \\ %) %)]
    (apply str (map escfn s))))

http://ideone.com/QXbbB

Disclaimer: I haven't tested this extensively so you may want to get a second opinion before using this code to sanitize potentially evil strings.

Alex Jasmin
  • 39,094
  • 7
  • 77
  • 67
-1

I should say first off that I use neither ClojureScript nor Javascript, but a quick search for ClojureScript regex support brought me to this page: https://github.com/clojure/clojurescript/wiki/Differences-from-Clojure, where under the "Other Functions" section, it says: "ClojureScript regular expression support is that of JavaScript", providing this link: http://www.w3schools.com/jsref/jsref_obj_regexp.asp. That next link seems to provide you with what you would be looking for (as a person who doesn't use JavaScript, I am cautious to say for certain).

Edit
Ooh, and maybe the answer to this old question here: Converting user input string to regular expression will give you a more complete answer.

Community
  • 1
  • 1
Omri Bernstein
  • 1,893
  • 1
  • 13
  • 17