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'.
?= 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).
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.
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.
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.
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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With