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
  • 4,789
  • 10
  • 45
  • 69

4 Answers4

19

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
  • 68,613
  • 12
  • 97
  • 138
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
  • 166,785
  • 24
  • 204
  • 249
1

You could try:

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

\b matches a word boundary.

Mauritz Hansen
  • 4,504
  • 3
  • 27
  • 34
1

Try =

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

Just added start and end points for the string.

vks
  • 65,133
  • 10
  • 87
  • 119