Regex to match a string with 2 capital letters only

Try =

^[A-Z][A-Z]$ 

Just added start and end points for the string.


You need to add word boundaries,

\b[A-Z]{2}\b

DEMO

Explanation:

  • \b Matches between a word character and a non-word character.
  • [A-Z]{2} Matches exactly two capital letters.
  • \b Matches between a word character and a non-word character.

You could use anchors:

^[A-Z]{2}$

^ matches the beginning of the string, while $ matches its end.


Note in your attempts, you used [A-Z]{2, 2} which should actually be [A-Z]{2,2} (without space) to mean the same thing as the others.


You could try:

\b[A-Z]{2}\b 

\b matches a word boundary.

Tags:

Python

Regex