0

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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
user9671207
  • 33
  • 2
  • 8

1 Answers1

1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875