[英]Regex to match paths that don't match a specific pattern: Express Router
I want to ignore all paths of the form /foo/* on my express server. 我想忽略我的快速服务器上的/ foo / *形式的所有路径。 So I want to do
所以我想做
app.get('someRegexThatDoesntMatchFoo/*', routes.index)
I have tried 我努力了
app.get('/^\(\(.*foo/.*\)\@!.\)*$', routes.index);
but that didnt work-- it doesn't catch all-routes-besides-foo
and apply routes.index
instead i get a CANNOT GET bar
for any /bar
request 但这没有工作 - 它没有捕获
all-routes-besides-foo
并应用routes.index
而不是我得到一个CANNOT GET bar
任何/bar
请求
Any suggestions? 有什么建议么?
Thanks! 谢谢!
The following regex will match any path except those starting with /foo/ 以下正则表达式将匹配除以/ foo /开头的路径之外的任何路径
app.get(/^\/([^f][^o][^o]|.{1,2}|.{4,})\/.*$/, routes.index);
I assume that this is a standard javascript regex. 我假设这是一个标准的javascript正则表达式。
The first answer was not correct, that's why I post again. 第一个答案是不正确的,这就是我再次发布的原因。
The following regex will match any path except those starting with /foo/ 以下正则表达式将匹配除以/ foo /开头的路径之外的任何路径
app.get(/^\/([^f]|f[^o]|fo[^o]|foo[^/]).*$/, routes.index);
This solution gets more and more complex as the size of the string increases. 随着字符串大小的增加,此解决方案变得越来越复杂。
Anyway, looking here for a regex is not the right thing. 无论如何,在这里寻找一个正则表达式是不对的。
When configuring routes, you have always to start with the more special rule and finish with the most general. 配置路由时,您始终要从更特殊的规则开始,并以最常规的方式完成。 Like this you would not run in such issues.
像这样你就不会遇到这样的问题。
You first have to define your route for /foo/*
and after that for all others *
. 你首先要确定你的路线
/foo/*
,之后,所有其他*
。
Define a route for /foo/*
to handle (or not), then use a wildcard to handle everything else. 定义
/foo/*
处理(或不处理)的路由,然后使用通配符处理其他所有内容。
app.get('/foo/*', function(req,res) {
//ignore or handle
});
app.get('*', routes.index);
负向前瞻性regexps工作(至少在现代):
app.get(/^(?!\/foo\/)/, routes.index);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.