Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

290
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!