Search code examples
pythonpython-re

Python Re module: find words after specific word


I would like to search words after specific words with re module. (without using list comprehensions)

sentence = "I like you, I like your smile, I like stack o v e r flow"

# expected outcome
['you', 'your smile', 'stack o v e r flow']

I managed to get a single word after 'I like', but couldn't figure out how to get the whole sentence when there are different numbers of words.

# my code
re.compile(r'I like (\w+)').findall(sentence)

# my output
['you', 'your', 'stack']

Solution

  • With this regexp I get the correct output:

    sentence = "I like you, I like your smile, I like stack o v e r flow"
    re.compile(r'I like ([\w\s]+)').findall(sentence)
    

    You need to consider an optional space (\s) together with the word character(\w). This pattern occurs at least once ([\w\s]+).