如何使用CASE或CORE.Match使用重新匹配
我正在尝试在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-&gt; html“#foo”)
>
但是,这可行!
(defn markdown->html [markdown-line]
(if
(boolean (re-matches #"#\s+\w+" markdown-line)) (str "<h1>")))
对于上面的所有测试,我会像这样调用该功能:(Markdown-&gt; html“#foo”)
有人知道我在做什么错吗?
I am trying to implement pattern-matching in Clojure. My preference is to use core.match
to match on a given regex pattern. I tried this:
(defn markdown->html [markdown-line]
(match [markdown-line]
[(boolean (re-matches #"#\s+\w+" markdown-line))] (str "<h1>")))
This does not even compile properly. I pivoted to a case conditional:
(defn markdown->html [markdown-line]
(case markdown-line
(boolean (re-matches #"#\s+\w+" markdown-line)) (str "<h1>")))
However, that did not give me the expected results when I invoke it with this: (markdown->html "# Foo")
However, this works!
(defn markdown->html [markdown-line]
(if
(boolean (re-matches #"#\s+\w+" markdown-line)) (str "<h1>")))
For all the tests above, I am invoking the function like so: (markdown->html "# Foo")
Does anyone know what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅
例如:
和
clojure.core.core.match/match
是相似的,所以我想说这两个都是错误的工具。如果您要编写将github markdown转换为html的功能,请检查 可以帮助您:
甚至更好,使用
$
组:顺便说一句,可以这样改进您的示例:
如果缺少 else 分支,所以更好时
;您不必使用
boolean
,因为false
或nil
被视为逻辑false,任何其他值都是逻辑的,没有将一个字符串包裹在str
中的原因。编辑:标题功能
&lt; h1&gt;
-&lt; h6&gt;
:See the docs for
case
:For example:
And
clojure.core.match/match
is similar, so I'd say both are wrong tool for your problem.If you're trying to write function for converting Github markdown to HTML, check
clojure.string/replace
, which can help you:Or even better, using
$
for group:By the way, your example can be improved like this:
If
is missing else branch, sowhen
is better; you don't have to useboolean
, becausefalse
ornil
are considered as logical false and any other value is logical true and there is no reason to wrap one string instr
.EDIT: Function for headers
<h1>
-<h6>
: