1

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.com/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);

3 Answers 3

6

To 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

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, I have one more question what If I want accept queries only with a-c (lowercase)? I thought that it will work like that ,but it doesn't... I don't know regex very well.
Change [a-z] into [a-c] and it will only accept characters a, b and c
Sorry I made mistake I didn't want to write a-c I thought a-z ,but only lower case not somethig like /aBcd.
You are right, Express treats all urls as case insensitive by default. I will edit my post
2

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.

1 Comment

I typed in route=/:id/? and path=/5 and it says the path doesn't match the route...
0

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 compare string from beginning. Or, in [^\d] block, this means inversion, in this case this is any symbol except number.

remove ^ symbol

1 Comment

It works ,but when I enter /aDcd it is correct. Shouldn't be this regex only for lowercase letters?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.