Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
express router with regex expression to match multiple paths
router.post(/^\/(path_A|path_B)/, verify, async (req, res) => {
  ...
});

The goal is to match the path path_A and path_B in the same route. I don't think that the regex is written correctly. Can someone double check?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your code:

router.post(/^\/(path_A|path_B)/, verify, async (req, res) => {
  ...
});

Will work just fine to match either /path_A or /path_B. I've verified it by running it locally. Some notes on this:

  1. The ^ is required if you want to ensure your regex starts at the beginning of the path and cannot match only something in the middle of the path. For example, without the ^, it would match /X/path_A or /www/path_B.

  2. Your existing regex will also match /path_AAAA and /path_Bxxx because it does not specify anything after the match. If you only wanted to match just /path_A or /path_B with nothing afterwards, then you could put a $ at the end of your regex. These are just regular regexes so they will just match what any old regex would match. All the normal regex rules apply.

  3. If you specify a string instead of a regex, then your matching options are more limited (to a subset of regex stuff that the path to regex library supports and Express will require more complete matches by testing for additional conditions. But, if you use a regex object, then all of that is up to you.


FYI, I tried going without the native regex object like this and letting the built-in path-to-regexp handle the details:

router.post("/(path_A|path_B)", verify, async (req, res) => {
  ...
});

And, it will not work. In fact, it gets a run-time error when executing the router.post() and parsing the path. In diagnosing the issue, it appears to be an old bug in the path-to-regexp library that has long since been fixed, but Express loads the older version of the library that has this problem. So, for now, what you're trying to do appears to require the full regular expression object.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!