Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

293
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda