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

124
Visualizações
Ensure regex test fails even if string matches an earlier portion of the pattern

Apologies if the title is too vague, I don't know the terminology for this issue so any suggestions would be much appreciated!

Current pattern: ^(?:\/[^\/]*){2}(?:\/tree|)

Target language/platform: JS

Inputs and expected results:

1. /foo/bar                                 pass
2. /foo/bar/tree/baz                        pass
3. /foo/bar/tree/baz/foobar                 pass

4. /foo/bar/blob                            fail
5. /foo/bar/blob/x.js                       fail

Testing mechanism: pattern.test(entryString);

These are GitHub paths, and what I'm trying to do is match a repository (/foo/bar), or any subpath (/foo/bar/tree/baz/....). The third path segment should be tree if it exists, else, the test should fail.

The problem with the pattern above is that the 4th & 5th items still pass despite matching neither condition of that pattern. It's probably some silly mistake, but can't figure out what it is.

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

You could optionally match /tree followed by optional repetitions or / and other chars than / and assert the end of the string $ to prevent partial matches.

^(?:\/[^\/]*){2}(?:\/tree(?:\/[^\/]*)*)?$

Explanation

  • ^ Start of string
  • (?:\/[^\/]*){2} Repeat 2 times / and optionally any char except /
  • (?: Non capture group
    • \/tree Match /tree
    • (?:\/[^\/]*)* Optionally repeat / any char except /
  • )? Close the non capture group and make it optional
  • $ End of string

Regex demo

If you don't need to match the whole string, you can assert the end of the string in the alternation:

^(?:\/[^\/\n]*){2}(?:\/tree\/|$)
about 4 years ago · Santiago Gelvez 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