Search code examples
pythonregexpython-re

Regex - question about finding every word in a string that begins with a letter


import re

random_regex = re.compile(r'^\w')
x = random_regex.findall('RoboCop eats baby food. BABY FOOD.')
print(x)

This is the code I have, following along on Automate the Boring Stuff with Python. However I kind of side-tracked a bit and wanted to see if I could get a list of all the words in the string passed in random_regex.findall() that begin with a word, so I wrote \w for the regex pattern. However for some reason my output only prints "R" and not the rest of the letters in the string, Would anyone be able to explain why/tell me how to fix this problem?


Solution

  • import re
    random_regex = re.compile(r'\w+')
    x = random_regex.findall('RoboCop eats baby food. BABY FOOD.')
    print(x)