How can I get regex matching positions in ClojureScript?

In Clojure, I could use something like this solution: Compact Clojure code for regular expression matches and their position in a string , i.e. creating re-matcher and extracting information from it, but re-matching is not implemented in ClojureScript. What would be a good way to accomplish the same thing in ClojureScript?

Edit:

I ended up writing an extra function to save the regex modifiers, as it is absorbed by re-pos :

 (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)))) 
+4
source share
1 answer

You can use the .exec method of the JS RegExp object. The return match object contains the index property, which corresponds to the match index in the string.

Currently clojurescript does not support building regular expressions using the g flag (see CLJS-150 ), so you need to use the RegExp constructor. The following is an implementation of the re-pos clojurescript function from the linked page:

 (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"} 
+7
source

Source: https://habr.com/ru/post/1501607/


All Articles