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

239
Visualizações
How to use negative lookahead (NOT lookbehind) to match a string that does NOT contain a given substring at a specific position?

I'd like to match certain file types (e.g., ".txt") with a non-empty root name that doesn't end in a particular substring (e.g., "-bad"). With negative lookbehind support, the solution is simple:

/.(?<!-bad)\.txt$/

Safari, however, still does not support negative lookbehinds. Ugh. How could I achieve the same result using a negative lookahead? I'd like to do this with a single regular expression. Please do not provide any non-regex or multi-step solutions.

The test code below shows that I'm close, but one test is still failing. 😕

const regex = /.((?!-bad).{4})\.txt$/;
const tests = [
  ['this-file-bad.txt', false],
  ['this-file.txt', true],
  ['.txt', false],
  ['f.txt', true]
];

const results = tests.map(([input, expected]) => ((regex.test(input) === expected) ? '✅' : '❌') + input);
console.log(results.join('\n'));

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use

^(?!.*\-bad\.txt$).+\.txt$

Demo1

The regular expression reads as follows:

  • Match the beginning of the string (^)
  • Use a negative lookahead ((?!...)) to assert that the string does not end "-bad.txt"
  • Match one or more characters followed by ".txt" at the end of the string.

To check for any of several file suffices at the same time (which, based on your comment below, may be helpful) you could write, for example:

^(?=.*\.(txt|pdf|csv|docx|html|jpeg)$)(?!.*\-bad\.\1$).+\.\1$

The positive lookahead at the beginning has the sole purpose of capturing the file suffix at the end of the string so that a back-reference can be used in the negative lookahead and at the end.

Demo2

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