Regex 正则数和单位

Regex 正则数和单位,regex,clojure,Regex,Clojure,我不熟悉正则表达式,但我有从输入字符串中提取数字和单位的想法。我最初的想法是构造一系列可能感兴趣的单元。然后在输入中查找单位后面的数字序列。但是,我不确定如何将数组和regex中的数字结合起来 我很可能计划使用core.matrix数组函数构造数组。尽管我不确定这是否是数字和单位正则表达式耦合的最佳方法 例如,我们正在寻找100公斤袋装大米 或者,我们可能在这里发现了一袋100公斤的大米 数字和单位之间可能存在空白 正则表达式[0-9]+?[a-zA-Z]+将找到数字,然后您可以使用正则表达式拆

我不熟悉正则表达式,但我有从输入字符串中提取数字和单位的想法。我最初的想法是构造一系列可能感兴趣的单元。然后在输入中查找单位后面的数字序列。但是,我不确定如何将数组和regex中的数字结合起来

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

例如,我们正在寻找100公斤袋装大米

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

数字和单位之间可能存在空白

正则表达式[0-9]+?[a-zA-Z]+将找到数字,然后您可以使用正则表达式拆分结果?正则表达式[0-9]+?[a-zA-Z]+将找到数字,然后您可以使用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"})
编辑

重新阅读你的问题后,我发现你想要一组动态的单位。下面是一个例子:

(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"})
使用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"})
编辑

重新阅读你的问题后,我发现你想要一组动态的单位。下面是一个例子:

(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"})

抱歉,您确实需要更具体地说明您打算用示例提取什么!抱歉,您确实需要更具体地说明您打算用示例提取什么!