Search code examples
pythonfindall

How to find the whole word with re.findall?


this is my code:

str_list = 'Hallo Welt Halloer' 
conversations_counter = len(re.findall("Hallo", str_list))
print(conversations_counter)

The result is 2! But I just want to have a match for the whole word 'Hallo'. The word 'Hallo' in the word 'Halloer' should not be counted.

Hallo = Hallo -> 1 Halloer <> Hallo -> 0

How to achieve this?

Thanks


Solution

  • Add a 'word boundary' to your regex:

    Hallo\b
    

    Don't forget to set the regex using r, not as string:

    import re
    
    str_list = 'Hallo Welt Halloer' 
    conversations_counter = len(re.findall(r"Hallo\b", str_list))
    print(conversations_counter) # 1
    

    Try it online!