加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在ClojureScript中获取正则表达式匹配的位置?

发布时间:2020-12-14 06:02:00 所属栏目:百科 来源:网络整理
导读:在Clojure中,我可以使用类似这样的解决方案: Compact Clojure code for regular expression matches and their position in string,即创建重新匹配器并从中提取信息,但重新匹配器似乎没有在ClojureScript中实现.在ClojureScript中完成同样的事情有什么好方
在Clojure中,我可以使用类似这样的解决方案: Compact Clojure code for regular expression matches and their position in string,即创建重新匹配器并从中提取信息,但重新匹配器似乎没有在ClojureScript中实现.在ClojureScript中完成同样的事情有什么好方法?

编辑:

我最后写了一个补充函数,以保留正则表达式的修饰符,因为它被吸收到重新定位:

(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 RegExp对象的 .exec方法.返回的匹配对象包含一个index属性,该属性对应于字符串中匹配的索引.

目前clojurescript不支持使用g mode标志构造正则表达式文字(请参阅CLJS-150),因此您需要使用RegExp构造函数.这是来自链接页面的重新发布函数的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"}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读