Q:

Behaviour of Python non-greedy regular expression

I'm using python version 3.4.1 and I don't understand the result of the following regular
expression:
import re
print(re.match("\[{E=(.*?),Q=(.*?)}\]","[{E=KT,Q=P1.p01},{E=KT2,Q=P2.p02}]").groups())
('KT', 'P1.p01},{E=KT2,Q=P2.p02')

I would expect the result to be
('KT', 'P1.p01')

but apparently the second .*? 'eats' all characters until '}]' at the end.
I would expect to stop at the first '}" character.
If I leave out the '[' and ']' characters the behavior is as I expect:
print(re.match("{E=(.*?),Q=(.*?)}","{E=KT,Q=P1.p01},{E=KT2,Q=P2.p02}").groups())

('KT', 'P1.p01')

A:

The \] forces a square bracket to be present in the match - and there only is one at the end of the string. The regex engine has to other option to match. If you remove it or make it optional (\]?), it stops at the closest }.

