Skip to content

Commit

Permalink
Added a utility function which transform a string into another which …
Browse files Browse the repository at this point in the history
…can be used in a regex without any special matching behavior other than matching the original string.
  • Loading branch information
green-coder committed Apr 4, 2019
1 parent b11dc55 commit 325b5dd
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/hopen/syntax/util.cljc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
(ns hopen.syntax.util
(:require [clojure.string :as str]))

(defn re-quote
"Escapes characters in the string that are not safe to use in a regex.
Function ported to Clojure from https://github.com/google/closure-library/blob/0257667129eded0cb9b86b4701e50c986b5db648/closure/goog/string/string.js#L1016"
[s]
(-> s
(str/replace #"[-()\[\]{}+?*.$\^|,:#<!\\]" #(str "\\" %))
(str/replace #"\x08", "\\x08")))
2 changes: 2 additions & 0 deletions test/hopen/runner.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
(:require [cljs.test :as t :include-macros true]
[doo.runner :refer-macros [doo-all-tests doo-tests]]
[hopen.renderer.xf-test]
[hopen.syntax.util-test]
[hopen.util-test]))

(doo-tests 'hopen.renderer.xf-test
'hopen.syntax.util-test
'hopen.util-test)
13 changes: 13 additions & 0 deletions test/hopen/syntax/util_test.cljc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
(ns hopen.syntax.util-test
(:require #?(:clj [clojure.test :refer [deftest testing is are]]
:cljs [cljs.test :refer [deftest testing is are]
:include-macros true])
[hopen.syntax.util :refer [re-quote]]))

(deftest re-quote-test
(are [input output]
(= (re-quote input) output)

"bonjour" "bonjour"
"{{}}" "\\{\\{\\}\\}"
"<%%>" "\\<%%>"))

0 comments on commit 325b5dd

Please sign in to comment.