Search code examples
pythonregex-greedy

Regex stops at first match


I am trying to capture both 'catwoman' and 'superman' but the match stops at the first instance. What can i do to capture both matches?

p3= re.compile(r"\w+(wo)?man")
t='what if catwoman and superman got married!'
r3=p3.search(t)
print(r3.group())

Solution

  • Use re.findall for finding all matches. Also, you have to redefine regular expression.

    Here is how it works:

    p3 = re.compile(r'(\w+man)')
    t = 'what if catwoman and superman got married!'
    r3 = p3.findall(t) # 'findall' corrected originally misspelt 'finadll'
    print(r3) # ['catwoman', 'superman']