clojure - 获取使用 Clojure 的读取字符串读取的字符串的 "unread"部分

标签 clojure tokenize

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]”

对于读者来说,相当于 restdrop 的是什么?

最佳答案

您可以将字符串包装在 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/

相关文章:

clojure/lein REPL 与 jline

clojure - 推荐 Clojure 的 Web 框架

c# - StreamReader 行和行分隔符

lucene - ElasticSearch 词干提取

java - 在java中用空格标记一个字符串

clojure - 什么是fn *?Clojure Bootstrap 如何?

clojure - "^:static"在 Clojure 中做什么?

clojure - var 或 ref/atom/agent 用于常量值?

ruby - 如何通过 Nokogiri 访问没有名称的文本

c++ - 使用 find 和 substr 函数进行解析