Clojure routing,bidi,我用于路由的正则表达式未完全匹配

时间:2019-04-11 13:58:08

标签: regex clojure routes bidi

在构建某些路由时我需要一些帮助,我有以下路由架构,

   (def my-routes

        ["/" {"" :home

              "info" :info

              "posts/" {"" :all-posts

                        [#"\d+" :tag-name] :post-by-tag

                        [#"\w+" :post-name] :post-by-name}}])

但是当我做一些测试时,正则表达式似乎有问题。例如:

    ;; testing the tag route
    (match-route my-routes "/posts/213")
    ;; => {:route-params {:tag-name "3"}, :handler :post-by-tag}

    ;; testing the name route
    (match-route my-routes "/posts/the-first-post")
    ;; => {:route-params {:post-name "-first-post"} , 
                          :handler :post-by-name}

因此,它似乎切断了“ /”之后的部分,而当我在正常比对检查中的比迪之外进行操作时,这似乎很好

    (re-matches #"\d+" "213")
     ;; => "213"

    ;; I do see that this regex wouldn't pass the example I used above, but 
    ;; the main matter is this weird behaviour seen in the routing.
    (re-matches #"\w+" "post")
    ;; => "post"

如果任何人都可以提供一些解析这些路由的正则表达式,将不胜感激

编辑

替换正则表达式并用match-route尝试后,似乎只返回最后一个字母:

(use 'bidi.bidi)
;; => nil

(def my-routes
  ["/" {"" :home

        "info" :info

        "posts/" {"" :all-posts
                  [#"\d+" :tag-name] :post-by-tag
                  [#"[\w\-]+" :post-name] :post-by-name}

        }]

)
;; => #'user/my-routes

(match-route my-routes "/posts/the-first-post")
;; => {:route-params {:post-name "t"}, :handler :post-by-name}

1 个答案:

答案 0 :(得分:1)

\w与减号不匹配:

(re-matches #"\w+" "the-first-post" )
=> nil

您可能想改用[\w\-]

(re-matches #"[\w\-]+" "the-first-post" )
"the-first-post"