4

在 Clojure 中,我可以使用类似这样的解决方案:Compact Clojure code for regular expression matchs and their position in string,即创建 are-matcher并从中提取信息,但重新匹配器似乎没有在 ClojureScript 中实现。在 ClojureScript 中完成同样事情的好方法是什么?

编辑:

我最终编写了一个补充函数,以保留正则表达式的修饰符,因为它被吸收到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

1 回答 1

10

可以使用.execJSRegExp对象的方法。返回的匹配对象包含一个index属性,该属性对应于字符串中匹配项的索引。

目前 clojurescript 不支持使用g模式标志构造正则表达式文字(参见CLJS-150),因此您需要使用RegExp构造函数。re-pos这是来自链接页面的函数的 clojurescript 实现:

(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"}
于 2013-09-11T09:09:23.843 回答