algorithmicCoder
algorithmicCoder

Reputation: 6789

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. 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

Any suggestions?

Thanks!

Upvotes: 4

Views: 6322

Answers (4)

Jacob
Jacob

Reputation: 78850

Negative lookahead regexps work (at least in modern times):

app.get(/^(?!\/foo\/)/, routes.index);

Upvotes: 3

Lorenz Meyer
Lorenz Meyer

Reputation: 19895

The first answer was not correct, that's why I post again.

Solution

The following regex will match any path except those starting with /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.

Recommended

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 *.

Upvotes: 3

max
max

Reputation: 6069

Define a route for /foo/* to handle (or not), then use a wildcard to handle everything else.

app.get('/foo/*', function(req,res) {
  //ignore or handle
});

app.get('*', routes.index);

Upvotes: 2

Lorenz Meyer
Lorenz Meyer

Reputation: 19895

The following regex will match any path except those starting with /foo/

app.get(/^\/([^f][^o][^o]|.{1,2}|.{4,})\/.*$/, routes.index);

I assume that this is a standard javascript regex.

Upvotes: 3

Related Questions