What is a regex to match a string that is either two or three characters long, of which at most one character is a digit and the rest are letters?
Examples of matching input:
T4
T4T
4TT
TT
Examples of non-matching input:
T
T44
T4TT
_4_
Use a negative look ahead to assert max 1 digit:
^(?!.*\d.*\d)[^\W_]{2,3}$
Explanation:
(?!.*\d.*\d)
means "assert that after this point there is not 2 digits"\W
means "a non-word character" - a "word character" is any letter, digit or the underscore. This is the opposite of \w
, which means "a word character". \W
is the same as [^\w]
[^\W_]
means "neither a non-word character nor an underscore" It is identical to [0-9a-zA-Z]
, but shorter to write{2,3}
means "between 2 and 3 (inclusive) of the previous term"I'm pretty sure this is the shortest solution.
See live demo with your test cases.
Using negative lookahead you can use this regex:
^(?![a-zA-Z]*\d+[a-zA-Z]*\d)[a-zA-Z\d]{2,3}$
RegEx Demo
(?![a-zA-Z]*\d+[a-zA-Z]*\d)
is negative lookahead to fail the match if there are more than 1 digit in input[a-zA-Z\d]{2,3}
will match 2 or 3 characters that consist of letters and digits.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With