Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for two or three character string of which 0 or 1 may be a digit

Tags:

regex

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_
like image 455
pythonic metaphor Avatar asked Sep 11 '25 20:09

pythonic metaphor


2 Answers

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.

like image 95
Bohemian Avatar answered Sep 14 '25 11:09

Bohemian


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.
like image 26
anubhava Avatar answered Sep 14 '25 12:09

anubhava