9

I want to write a regex which will match a string only if the string consists of two capital letters.

I tried - [A-Z]{2}, [A-Z]{2, 2} and [A-Z][A-Z] but these only match the string 'CAS' while I am looking to match only if the string is two capital letters like 'CA'.

Siddharth
  • 5,009
  • 11
  • 49
  • 71

4 Answers4

21

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.

Jerry
  • 70,495
  • 13
  • 100
  • 144
6

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.
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

You could try:

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

\b matches a word boundary.

Mauritz Hansen
  • 4,674
  • 3
  • 29
  • 34
1

Try =

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

Just added start and end points for the string.

vks
  • 67,027
  • 10
  • 91
  • 124