编写以下函数的惯用方法是什么?
(split-first #"." "abc.def.ghi") ;;=>["abc", "def.ghi"]
(split-last #"." "abc.def.ghi") ;;=>["abc.def", "ghi"]
使用split
有一个明显的(丑陋?)解决方案,但我确定有更优雅的解决方案吗?也许使用正则表达式/ indexOf / split-with?
答案 0 :(得分:1)
对于分裂优先,最好的方法是:
select title, cost, pageUrl
from products
where cost between 100 and 125
and (title like '%something%' or pageUrl like '%something%');
split-last的一种方法是使用否定先行断言:
(defn split-first [re s]
(clojure.string/split s re 2))
(split-first #"\." "abc.def.ghi")
=> ["abc" "def.ghi"]
(split-first #"<>" "abc<>def<>ghi")
=> ["abc" "def<>ghi"]
答案 1 :(得分:1)
如果你不一定需要正则表达式匹配,那么这将起作用:
(defn index-of
[^String s c]
(.indexOf s c))
(defn last-index-of
[^String s c]
(.lastIndexOf s c))
(defn split-at-index-fn
[f c s]
(let [i (f s c)]
; I do not know what you want returned if no match is found
(when-not (neg? i)
[(.substring s 0 i) (.substring s (inc i))])))
(def split-first
(partial split-at-index-fn index-of))
(def split-last
(partial split-at-index-fn last-index-of))
这不是很惯用,因为它主要只是Java互操作。