簡體   English   中英

如何在ClojureScript中獲取正則表達式匹配的位置?

[英]How can I get the positions of regex matches in ClojureScript?

在Clojure中我可以使用類似這樣的解決方案: 用於正則表達式匹配的緊湊Clojure代碼及其在字符串中的位置 ,即創建re-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))))

您可以使用JS RegExp對象的.exec方法。 返回的匹配對象包含一個index屬性,該屬性對應於字符串中匹配的索引。

目前clojurescript不支持使用g mode標志構造正則表達式文字(請參閱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"}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM