Vijay D
Vijay D

Reputation: 57

Regex for a string - length 9, Third character letter and remaining numeric

I am trying to create a RegEx to match a string with the following criterion

example:

a555444
B999999

example:

12B456789
16K456745

My regex:

^[a-zA-Z][0-9]{6}$

This is what I have so far and its handling only first scenario. Please help me in constructing a regex to handle this requirement.

Upvotes: 1

Views: 2135

Answers (2)

Daria Pydorenko
Daria Pydorenko

Reputation: 1802

Try regex like that:

^([0-9]{2})?[a-zA-Z][0-9]{6}$

? shows that [0-9]{2} group is optional.

So if you have a string with length 7, this group doesn't exist. If you have a string with length 9 this group exists.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626896

You may use an alternation:

^([A-Za-z][0-9]{6}|[0-9]{2}[A-Za-z][0-9]{6})$

See the regex demo

Details

  • ^ - start of a string
  • ( - start of a grouping construct (you may add ?: after ( to make it non-capturing) that will match either...
    • [A-Za-z][0-9]{6} - an ASCII letter and then 6 digits
    • | - or
    • [0-9]{2}[A-Za-z][0-9]{6} - 2 digits, 1 letter, 6 digits
  • ) - end of the grouping construct
  • $ - end of string.

Upvotes: 2

Related Questions