Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda