Clojure 的(读取字符串)非常有用。
例如。(read-string "{:a 1 :b 2} {:c 3 :d 4} [1 2 3]")
会给我第一个对象,{:a 1 :b 2}
但是我怎样才能得到字符串的其余部分,即。 “{:c 3 :d 4} [1 2 3]”
对于读者来说,相当于 rest
或 drop
的是什么?
最佳答案
您可以将字符串包装在 StringReader
中,然后将其包装在 PushbackReader
中,然后read
来自该读者多次。
注意。下面的示例使用 clojure.edn/read
,因为这是一个仅限 edn 的阅读器,用于处理纯数据; clojure.core/read
主要用于读取代码,并且永远不应该与不受信任的输入一起使用。
(require '[clojure.edn :as edn])
(def s "{:a 1 :b 2} {:c 3 :d 4} [1 2 3]")
;; Normally one would want to use with-open to close the reader,
;; but here we don't really care and we don't want to accidentally
;; close it before consuming the result:
(let [rdr (java.io.PushbackReader. (java.io.StringReader. s))
sentinel (Object.)] ; ← or just use ::eof as sentinel
(take-while #(not= sentinel %)
(repeatedly #(edn/read {:eof sentinel} rdr))))
;= ({:a 1, :b 2} {:c 3, :d 4} [1 2 3])
关于clojure - 获取使用 Clojure 的读取字符串读取的字符串的 "unread"部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39353421/