Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consecutive uppercase letters regex

I'm trying to use Regular expressions to find three consecutive uppercase letters within a string.

I've tried using:

\b([A-Z]){3}\b  

as my regex which works to an extent.

However this only returns strings by themselves. I also want it to find three consecutive uppercase letters nested within a string. i.e thisISAtest.


1 Answers

I wonder why you have those word boundaries in your regexp \b? Word boundaries ensure that an word character is followed by a non-word character (or vice versa). Those are what prevents thisISAtest from being matched. Remove them and you should be good!

([A-Z]){3}

Another thing is that I'm not sure why you're using a capture group. Are you extracting the last letter of the three uppercase letters? If not, you can simply use:

[A-Z]{3}

You don't necessarily need groups to use definite quantifiers. :)

EDIT: To prevent more consecutive uppercase letters, you can make use of negative lookarounds:

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

(?<![A-Z]) makes sure there's no preceeding uppercase letter;

(?![A-Z]) makes sure there's no following uppercase letter.

like image 123
Jerry Avatar answered Mar 29 '26 15:03

Jerry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!