我想要在nodejs中使用超级简单的过滤器来表达路由路径。参数必须为word1或word2。
测试于:https://forbeslindesay.github.io/express-route-tester/
带有表达式:test /:gender(\ b(word1 | word2)\ b)
路径:test / word2
而且一切正常。 “路径与路线匹配”
但是在代码中:
router.get('^/test/:gender(\b(word1|word2)\b)', function (req, res, next){//something})...;
我得到404(从express重定向,如果参数不正确,则应该重定向!)。
注意1:删除正则表达式字符串,它可以工作。
注2:我DID设法使另一个过滤器起作用。它必须像:“ word1-word2 [-moreWords]。我用
router.get('^/test/:user_name(*[a-zA-Z0-9][-]*[a-zA-Z0-9])', function (req, res, next) {//something});
并且可以正常工作。
注意3:我也对其进行了测试(我首先在中编写它们):https://regex101.com/,并且它们当然起作用。
那我该怎么办呢?
最佳答案
您可以使用
'^/test/:gender(word1|word2)\\b'
请注意,在
gender
和word
之间没有单词边界,只能保留结尾的单词边界。要定义单词边界,您需要一个文字反斜杠,后跟
b
,因此在字符串文字内部,您应该编写两个连续的反斜杠符号。