Search code examples
pythonregexstringsearchfindall

How to find all the exact matches in a given string using python Regex


I am trying to fetch all the 3 character words from my string, but getting only first occurrence

import re
a="AAA BBBBBBBBBB CCCCCCC DDD FFF"
print(re.findall('(^[A-Z]{3})',a))

Actual output:

['AAA']

Expected Output is:

['AAA','DDD','FFF']

Solution

  • ^[A-Z]{3} will match only 3 characters from the start of the string.

    Try re.findall(r'\b[A-Z]{3}\b', a) which will match word boundaries appropriately.