我想使用用户定义的正则表达式模式来定义 edn 文件中的日期,以便使用 malli 进行验证。
我如何在 core.clojure 中定义此模式,以便我可以在 edn 文件中使用它。
这就是我之前的 edn 文件的样子。
(def reading-schema
[:map
[:readingDate :re #"\d{4}-\d{2}-\d{2}"]
[:readingType string?]
[:readingPrecision string?]
[:readingEstimate string?]])
(def readingDetails-schema
[:map
[:readingCode string?]
[:readingNumber string?]
[:readingCheck string?]
[:readings [:vector reading-schema]]])
但我无法将其加载到 core.clj。如何解决这个问题?一种方法是在 clojure 中定义。但我不知道该怎么做。
假设这就是我定义 /edn 文件的方式,使所有模式都位于一个位置。
{
:reading-schema [:map
[:readingDate :re #"\d{4}-\d{2}-\d{2}"]
[:readingType string?]
[:readingPrecision string?]
[:readingEstimate string?]]
:readingDetails-schema [:map
[:readingCode string?]
[:readingNumber string?]
[:readingCheck string?]
[:readings [:vector reading-schema]]]
}
在 core.clj 中,我使用 aero 库来调用它,malli 使用该库来调用任何 edn 文件。
编辑:
这是我面临的错误:
Execution error at aero.core/read-pr-into-tagged-literal (core.cljc:180).
No dispatch macro for: "
EDN 不支持所有阅读器宏(或“功能”)(查看内置标记元素 https://github.com/edn-format/edn#built-in-tagged-elements) Clojure 阅读器支持。但您可以轻松添加自己的读者(请参阅:readers
of opts
):
user=> (doc clojure.edn/read)
-------------------------
clojure.edn/read
([] [stream] [opts stream])
Reads the next object from stream, which must be an instance of
java.io.PushbackReader or some derivee. stream defaults to the
current value of *in*.
Reads data in the edn format (subset of Clojure data):
http://edn-format.org
opts is a map that can include the following keys:
:eof - value to return on end-of-file. When not supplied, eof throws an exception.
:readers - a map of tag symbols to data-reader functions to be considered before default-data-readers.
When not supplied, only the default-data-readers will be used.
:default - A function of two args, that will, if present and no reader is found for a tag,
be called with the tag and the value.
例如:添加一个阅读器re
,然后可以将其放置在字符串之前,如下所示#re
在您的 EDN 文件中。
(require '[clojure.edn :as edn])
(let [re (edn/read-string
{:readers {'re re-pattern}} ; XXX
(slurp "schema.edn"))]
(assert (re-matches re "2022-01-01")))
使用这个schema.edn
#re "\\d{4}-\\d{2}-\\d{2}"
(注意\
在原始正则表达式中 - 在字符串中您需要转义它们)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)