How to get all occurances of group with regex in Python?

From code:

myStr = "one two four five"
myPattern = r'\w*\s(two\s|three\s|four\s)*\w*'
matched =, myStr)

if matched:
    res =

I get "four ", but I want to get ["two ", "four "]

How can I do it?

>Solution :

As all your surrounding word characters are optional, you can use re.findall and assert a whiteapace char to the left and match the trailing one:


Regex demo

import re

myStr = "one two four five"

print(re.findall(pattern, myStr))


['two ', 'four ']

Leave a Reply