Reputation: 5219
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
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
Reputation: 174706
You need to add word boundaries,
\b[A-Z]{2}\b
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