Regex to match between 2 and 5 characters, one of which must be alphabetic

Viewed 825

I'm not great with regex and the following has me stumped.

I need to find all the matches in a string that are between 2 and 5 characters [A-Z0-9] only, and must contain at least one alphabetic character [A-Z]

So

A1 - Match
AAA - Match
AAAAAA - No Match
A1234 - Match
123 - No Match
A123A - Match
A - No Match
1 - No Match
A1B2C3 - No Match

I have tried this:

([A-Z0-9]*[A-Z][A-Z0-9]*){2,5}

But it doesnt limit the total length of the match to between 2 and 5 characters

2 Answers

You can use

\b(?=\d*[A-Z])[A-Z\d]{2,5}\b
\b(?=[A-Z0-9]{2,5}\b)[A-Z0-9]*[A-Z][A-Z0-9]*\b

See the regex demo #1 and the regex demo #2. Details:

  • \b - word boundary
  • (?=\d*[A-Z]) - after zero or more digits, there must be an uppercase ASCII letter
  • (?=[A-Z0-9]{2,5}\b) - there must be 2 to 5 alnum chars up to the word boundary
  • [A-Z0-9]* - zero or more uppercase ASCII letters or digits
  • [A-Z] - an uppercase ASCII letter
  • [A-Z\d]{2,5} - two to five uppercase ASCII letters or digits
  • \b - word boundary.

See the Python demo:

import re
text = "A1 AAA....A1234!!!!~A123A abc,AAAAAA,123,A,1,A1B2C3"
print(re.findall(r'\b(?=[A-Z0-9]{2,5}\b)[A-Z0-9]*[A-Z][A-Z0-9]*\b', text))
# => ['A1', 'AAA', 'A1234', 'A123A']

Try this one ^([A-Z][A-Z0-9]{1,4}|[A-Z0-9][A-Z][A-Z0-9]{,3}|[A-Z0-9]{1,2}[A-Z][A-Z0-9]{,3}|[A-Z0-9][A-Z][A-Z0-9])$

Related