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

291
Visualizações
RegEx if then else for conditional test depending on first character

I should allow 2 different input strings formats, with each their own validation. So eg:

AA2222222222222222

and

2222222222222222

This means that if the first character is a letter, I should validate for ^[a-zA-Z]{2}\d{16}$. If the first character is numeric, I should validate for d{16}.

I tried to write it in an conditional regex:

^(([a-zA-Z])(?([a-zA-Z])^[a-zA-Z]{2}\d{16}$|d{16})

but I get a pattern error and can't figure out what exactly is wrong.

Any insight would be apreciated

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

0

I tried to write it in an conditional regex

JavaScript doesn't support regular expression conditional syntax, so (?ifthen|else) doesn't work in JavaScript.

This means that if the first character is a letter, I should validate for ^[a-zA-Z]{2}\d{16}$. If the first character is numeric, I should validate for d{16}.

Since the \d{16} part is the same, you can just make the [a-zA-Z]{2} part optional:

/^(?:[a-zA-Z]{2})?\d{16}$/

That uses a non-capturing group around the [a-zA-Z]{2} and makes the entire group optional via the ? after it.

If the validation were different (say, maybe the version with the letters at the start only does \d{14}), you could use an alternation:

/^(?:[a-zA-Z]{2}\d{14}|\d{16})$/

(Beware the gotcha: Without the non-capturing around around the alternation, the ^ would be part of the first alternative but not the second, and the $ would be part of the second alternative, but not the first.)

But in your specific case, you don't need that.

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