在 Clojure 中我可以使用类似这样的解决方案:用于正则表达式匹配及其在字符串中的位置的紧凑 Clojure 代码 https://stackoverflow.com/questions/3262195/compact-clojure-code-for-regular-expression-matches-and-their-position-in-string,即创建一个re-matcher
并从中提取信息,但重新匹配器似乎没有在 ClojureScript 中实现。在 ClojureScript 中完成同样事情的好方法是什么?
Edit:
我最终编写了一个补充函数,以便保留正则表达式的修饰符,因为它被吸收到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))))
您可以使用.exec https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/execJS的方法RegExp
目的。返回的匹配对象包含一个index
与字符串中匹配项的索引相对应的属性。
目前 clojurescript 不支持使用以下内容构造正则表达式文字g
模式标志(参见CLJS-150 http://dev.clojure.org/jira/browse/CLJS-150),所以你需要使用RegExp
构造函数。这是 clojurescript 的实现re-pos
链接页面的功能:
(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"}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)