Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match a string with 2 capital letters only

Tags:

python

regex

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

like image 929
Siddharth Avatar asked Jul 21 '14 07:07

Siddharth


People also ask

What does ?= * Mean in regex?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

How do you match letters in regex?

Using character sets For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter.

What is the use of \\ in regex?

You also need to use regex \\ to match "\" (back-slash). Regex recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.

How do you find multiple occurrences of a string in regex?

Method 1: Regex re. To get all occurrences of a pattern in a given string, you can use the regular expression method re. finditer(pattern, string) . The result is an iterable of match objects—you can retrieve the indices of the match using the match.


2 Answers

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.

like image 130
Jerry Avatar answered Sep 25 '22 01:09

Jerry


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.
like image 36
Avinash Raj Avatar answered Sep 24 '22 01:09

Avinash Raj