I am trying to figure out Regex that will only accept below strings.
7 and 8 numbers: '1234567' and '12345678'
7 and 8 numbers that start with T: 'T234567' and 'T2345678'
7 and 8 numbers that start with D: 'D234567' and 'D2345678'
7 and 8 numbers that start with TD: 'TD34567' and 'TD345678'
Regex I have is:
/^(T|[0-9]){1}(D|[0-9]){1}([0-9]){5,6}$/
but it's not passing my unit test for 'D234567' and 'D2345678'
CodePudding user response:
You could write the pattern as:
^(?:\d{7,8}|[TD]\d{6,7}|TD\d{5,6})$
Explanation
^
Start of string(?:
Non capture group for the alternatives\d{7,8}
Match 7-8 digits|
Or[TD]\d{6,7}
Match eitherT
orD
and 6-7 digits|
OrTD\d{5,6}
MatchTD
and 5-6 digits
)
Close the non capture group$
End of string
CodePudding user response:
I actually figure it out right after posted this question. Simply added |D after T| so like this.
/^(T|D|[0-9]){1}(D|[0-9]){1}([0-9]){5,6}$/