How can I get the positions of regex matches in ClojureScript?
在Clojure中我可以使用类似这样的解决方案:用于正则表达式匹配的紧凑Clojure代码及其在字符串中的位置,即创建
编辑:
我最后编写了一个补充函数,以便保留正则表达式的修饰符,因为它被吸收到
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | (defn regex-modifiers "Returns the modifiers of a regex, concatenated as a string." [re] (str (if (.-multiline re)"m") (if (.-ignoreCase re)"i"))) (defn re-pos "Returns a vector of vectors, each subvector containing in order: the position of the match, the matched string, and any groups extracted from the match." [re s] (let [re (js/RegExp. (.-source re) (str"g" (regex-modifiers re)))] (loop [res []] (if-let [m (.exec re s)] (recur (conj res (vec (cons (.-index m) m)))) res)))) |
您可以使用JS
目前clojurescript不支持使用
1 2 3 4 5 6 7 8 9 10 11 | (defn re-pos [re s] (let [re (js/RegExp. (.-source re)"g")] (loop [res {}] (if-let [m (.exec re s)] (recur (assoc res (.-index m) (first m))) res)))) cljs.user> (re-pos"\\w+""The quick brown fox") {0"The", 4"quick", 10"brown", 16"fox"} cljs.user> (re-pos"[0-9]+""3a1b2c1d") {0"3", 2"1", 4"2", 6"1"} |