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

148
Visualizações
Match a line with a [ character, but don't match if it has a ] character

I thought this regex would match lines with a [, but not if it has a ]:

^.*\[.*(?!\]).*$

Instead, it's matching every line with a [ (shown in bold):

This [should match]. This line should match

This line shouldn't match.

This line shouldn't match. This line [shouldn't match.

How to fix that regex so that it doesn't match lines that have a ]?

This [should match]. This line should match

This line shouldn't match.

This line shouldn't match. This line [shouldn't match.

Demo: https://regexr.com/67qk7

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

0

This pattern ^.*\[.*(?!\]).*$ matches [ and the directly following .* will match the rest of the line.

Then at the end of the line it will assert not ] directly to the right, which is true because it already is at the end of the line. Then the .* is optional and it can assert the end of the string.

So it will match any whole line that has at least a single [

If you want to match pairs of opening till closing square brackets [...] and not allow any brackets inside it, or single brackets outside of it and matching at least a single pair, you can repeat 1 or more times matching pairs surrounded by optional chars other than square brackets.

^(?:[^\][\n]*\[[^\][\n]*\])+[^\][\n]*$

Regex demo

about 4 years ago · Juan Pablo Isaza Relatório

0

An alternate solution which is not super efficient but is a bit shorter:

^(?!.*\[[^\]\n]*$)[^[\n]*\[.+$

RegEx Demo

Explanation:

  • (?!.*\[[^\]\n]*$) fails the match if we get a [ without a closing ] anywhere
  • [^[\n]*\[ matches first [ in a line
about 4 years ago · Juan Pablo Isaza Relatório

0

"This regex would match lines with a [" (one or more), "but not if it has a ]" (one or more):

^[^\][\n]*\[[^\]\n]*$

Screenshot from Regex101

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