Search code examples
pythonregexoverlappingnon-greedy

Python, Regex: non-greedy not working when overlapping?


MCVE python snippet

import re
str = "aa {bb cc {dd} ee"
print(re.search("{.*}", str).group())
print(re.search("{.*?}", str).group())

Output is

{bb cc {dd}
{bb cc {dd}

However, I would have expected

{bb cc {dd}
{dd}

Why doesn't the additional ? make the Regex non-greedy? Has the overlapping something to do with this?


Solution

  • It is non-greedy, but non-greedy doesn't mean, "find the smallest thing that matches," it means, "find the smallest thing that matches starting from the first place in the string that has a match." The first open curly brace is the start of a match, and the smallest thing that matches from there is {bb cc {dd}.