Clojure - 编写 split-first 和 split-last 的惯用方式

nha*_*nha 2 split clojure

编写以下函数的惯用方式是什么?

(split-first #"." "abc.def.ghi") ;;=>["abc", "def.ghi"]
(split-last #"." "abc.def.ghi") ;;=>["abc.def", "ghi"]
Run Code Online (Sandbox Code Playgroud)

有一个明显的(丑陋的?)解决方案使用split,但我确信有更优雅的解决方案?也许使用 regexes/indexOf/split-with ?

too*_*kit 6

对于拆分优先,最好的方法是:

(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"]
Run Code Online (Sandbox Code Playgroud)

split-last 的一种方法是使用负前瞻断言:

(defn split-last [re s]
  (let [pattern (re-pattern (str re "(?!.*" re ")"))]
    (split-first pattern s)))

(split-last #"\." "abc.def.ghi")
=> ["abc.def" "ghi"]

(split-last #"<>" "abc<>def<>ghi")
=> ["abc<>def" "ghi"]
Run Code Online (Sandbox Code Playgroud)

  • 好主意,但您还必须“反转”正则表达式。现在您的解决方案仅适用于回文模式。 (3认同)