I have a simple regex that should match words made of letters (0-5) only however it doesn't seems to be working. How should the regex look and be used in ExpressJS? URL I am trying to validate may look like something/abcd
var express = require("express"),
app = express();
app.get("/:id(^[a-z]{0,5}$)", function(req, res) {
res.send("The right path!");
});
app.listen(8000);
I have a simple regex that should match words made of letters (0-5) only however it doesn't seems to be working. How should the regex look and be used in ExpressJS? URL I am trying to validate may look like something./abcd
var express = require("express"),
app = express();
app.get("/:id(^[a-z]{0,5}$)", function(req, res) {
res.send("The right path!");
});
app.listen(8000);
Share
Improve this question
edited May 7, 2016 at 19:42
0101
asked Jan 31, 2014 at 14:25
01010101
2,7114 gold badges29 silver badges34 bronze badges
3 Answers
Reset to default 6To set up an URL which accepts /
followed by up to five ascii characters, you could do like this:
var express = require("express"),
app = express();
app.get("/[a-z]{0,5}$", function(req, res){
res.send("Right path!");
});
app.listen(8000);
result:
GET http://localhost:8000/
Right path!
GET http://localhost:8000/abcde
Right path!
GET http://localhost:8000/abcdef
Cannot GET /abcdef
Note: Express does case insensitive routing by default. To change it, put this at the top of your script:
app.set('case sensitive routing', true);
Now, [a-z]
will match only lower case characters: GET /abc
but not GET /ABC
To make things clear: The original question is the valid syntax to match an express.js route in a
NAMED paramter
The only error is to have the start/end anchors within the RegExp. I think they are added automatically.
A nice tool to validate express routes says this is fine:
/:id([a-z]{0,5})
btw: To whoever downvoted the question: shame on you.
I would strongly suggest to use the "named param" syntax because app.param is a nice feature.
I don't know what app.get does, but if we are speaking about regular expressions:
^ can be situated at the first position. It means that need to pare string from beginning. Or, in [^\d] block, this means inversion, in this case this is any symbol except number.
remove ^ symbol