Question: I need a regex statement that will check for three capital letters in a row.

For example, it should match: ABC, aABC, abcABC

But it should not match: AaBbBc, ABCDE

At the moment this is my statement:

```
'[^A-Z]*[A-Z]{3}[^A-Z]*'

```

But this matches ABCDE. What am I doing wrong?

Answer: 
Regex
-----

```
(?<![A-Z])[A-Z]{3}(?![A-Z])

```

Explanation
-----------

I specified a *negative lookbehind* and a *negative lookahead* before and after the middle regex for three capitals in a row, respectively.

This is a better option compared to using a negated character class because it will successfully match even when there are no characters to the left or right of the string.

Online Demonstration
--------------------

[**DEMO**](https://regex101.com/r/rI1tY6/1)

---

As for the Python code, I haven't figured out how to print out the actual matches, but this is the syntax:

Using `re.match`:

```
>>> import re
>>> p = re.compile(r'(?<![A-Z])[A-Z]{3}(?![A-Z])')
>>> s = '''ABC
... aABC
... abcABCabcABCDabcABCDEDEDEDa
... ABCDE'''
>>> result = p.match(s)
>>> result.group()
'ABC'

```

Using `re.search`:

```
>>> import re
>>> p = re.compile(r'(?<![A-Z])[A-Z]{3}(?![A-Z])')
>>> s = 'ABcABCde'
>>> p.search(s).group()
'ABC'

```
Your regex has all explanation that what you are doing wrong

```
'[^A-Z]*[A-Z]{3}[^A-Z]*'

```

If ^ is used inside character set i.e [] which means ignore, so your regex would ignore if it starts A-Z (capital letters) either one or more at the starting. But as per your example, I think you don't want that

[A-Z]{3} means it will exactly match three capital letters in a row.

[^A-Z]\* means the same what I explained for the first one.

If you write '[A-Z]{3}' only, it would match exactly first three consecutive capital letters at anywhere in the string.

It would match ABCde abCDE aBCDe ABCDE
but it would not match abcDE ABcDE AaBcCc

Just try it.

**Example in Perl**

```
#!/usr/bin/perl
use strict;
use warnings;

my @arr = qw(AaBsCc abCDE ABCDE AbcDE abCDE ABC aABC abcABC);

foreach my $string(@arr){
  if($string =~ m/[A-Z]{3}/){
    print "Matched $string\n";
  }
  else {
    print "Didn't match $string \n";
  }
}

```

**Output:**

```none
Didn't match AaBsCc
Matched abCDE
Matched ABCDE
Didn't match AbcDE
Matched abCDE
Matched ABC
Matched aABC
Matched abcABC

```