正则表达式编号和单位

sun*_*ots 1 regex clojure

我是regex的新手,但有一个想法是从输入字符串中提取数字和单位.我最初的想法是构建一系列可能的兴趣单元.然后查看输入的数字序列,然后是单位.但是,我不确定如何在正则表达式中结合数组和数字的想法.

我很可能计划使用core.matrix数组函数构造数组.虽然我不确定这是否是数字和单位的正则表达式耦合的最佳方法.

一个示例输入可能是"我们正在寻找100公斤袋装大米".

或者,可能"在这里我们发现了一袋100公斤的大米."

因此,数字和单位之间可能存在空白区域.

She*_*ter 7

使用re-seq和正确的正则表达式应该让你开始:

(defn find-things [s]
  (map (fn [[_ count unit]] {:count count, :unit unit})
       (re-seq #"(\d+)\s*(kg|lb)" s)))

(find-things "here we are looking for 100kg bags of rice.")
; => ({:count "100", :unit "kg"})

(find-things "here we found a 100 lb bag of rice.")
; => ({:count "100", :unit "lb"})

(find-things "mix 99lb quinoa with 45kg barley.")
; => ({:count "99", :unit "lb"}
;     {:count "45", :unit "kg"})
Run Code Online (Sandbox Code Playgroud)

编辑

在重读你的问题后,我发现你想拥有一套动态的单位.这是一个例子:

(def units ["lb" "kg" "L" "ml"])
(def unit-match (clojure.string/join "|" units))
(def matching-str (str "(\\d+)\\s*(" unit-match ")")) ;; note escaped backslashes
(def matching-pattern (re-pattern  matching-str))

; replace the literal regexp in the function above with `matching-pattern`

(find-things "add 100ml to 900ml to yield 1 L!")
; => ({:count "100", :unit "ml"}
;     {:count "900", :unit "ml"}
;     {:count "1", :unit "L"})
Run Code Online (Sandbox Code Playgroud)