Siddharth
Siddharth

Reputation: 5219

Regex to match a string with 2 capital letters only

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'.

Upvotes: 9

Views: 34580

Answers (4)

vks
vks

Reputation: 67968

Try =

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

Just added start and end points for the string.

Upvotes: 1

Jerry
Jerry

Reputation: 71538

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.

Upvotes: 21

Mauritz Hansen
Mauritz Hansen

Reputation: 4774

You could try:

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

\b matches a word boundary.

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

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.

Upvotes: 6

Related Questions