Reputation: 57
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
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
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