我正在尝试在Clojure中实现模式匹配。我的首选是使用core.match来匹配给定的正则表达式。我试过这个:
(defn markdown->html [markdown-line]
(match [markdown-line]
[(boolean (re-matches #"#\s+\w+" markdown-line))] (str "<h1>")))这甚至不能正确编译。我转到一个有条件的案件:
(defn markdown->html [markdown-line]
(case markdown-line
(boolean (re-matches #"#\s+\w+" markdown-line)) (str "<h1>")))然而,当我调用它时,这并没有给出预期的结果:(markdown->html "# Foo")
然而,这是可行的!
(defn markdown->html [markdown-line]
(if
(boolean (re-matches #"#\s+\w+" markdown-line)) (str "<h1>")))对于上面的所有测试,我调用的函数如下:(markdown->html "# Foo")
有人知道我做错了什么吗?
发布于 2022-04-18 06:43:59
参见case的文档
测试常量不计算.它们必须是编译时的文字,不需要引用。
例如:
(case 'y
y "y"
c "c"
(x z) "x or z"
(a b) "a or b"
"default")而且clojure.core.match/match也是类似的,所以我认为两者都是解决问题的错误工具。
如果您正试图编写函数将Github标记转换为HTML,请选中clojure.string/replace,这可以帮助您:
(clojure.string/replace "# Foo bar
# Biz baz" #"#\s+([\w ]*)" (fn [[result group]] (str "<h1>" group "</h1>")))
=> "<h1>Foo bar</h1>\n<h1>Biz baz</h1>"甚至更好的是,对组使用$:
(clojure.string/replace "# Foo bar
# Biz baz" #"#\s+([\w ]*)" "<h1>$1</h1>")
=> "<h1>Foo bar</h1>\n<h1>Biz baz</h1>"顺便说一句,您的示例可以改进如下:
(defn markdown->html [markdown-line]
(when (re-matches #"#\s+\w+" markdown-line) "<h1>"))
(markdown->html "# Foo")
=> "<h1>"If缺少了other分支,所以when更好;您不必使用boolean,因为false或nil被认为是逻辑假的,任何其他值都是逻辑true,因此没有理由在str中包装一个字符串。
编辑:标头的函数<h1> - <h6>
(def text "# Foo bar
## Biz baz
### Foo baz
## Biz foo")
(clojure.string/replace text
#"(#{1,6})\s+([\w ]*)"
(fn [[result group1 group2]]
(let [tag (str "h" (count group1) ">")]
(str "<" tag group2 "</" tag))))
=> "<h1>Foo bar</h1>\n<h2>Biz baz</h2>\n<h3>Foo baz</h3>\n<h2>Biz foo</h2>"https://stackoverflow.com/questions/71907979
复制相似问题