Python regex dealing with "?"
Question: I know it's a pretty simple question. I happened to look at a regex example.

    
    
    import re
    pattern = r'^M?M?M?$'
    
    s = "MDM"
    
    re.search(pattern, s)
    

May I know why it doesn't match the string `s`? AFAIK, `?` is to specify 0 or
1 occurence. It matches MMM though.

However the same string matches when the pattern is `r'M?M?M?$'` or
`r'^M?M?M?'`. I am not getting what makes the difference here. Could someone
please explain?


Answer: `r'^M?M?M?$'` is the same as `r'^M{0,3}$'`. So, your pattern accepts `'', 'M',
'MM', 'MMM'` strings.

`r'M?M?M?$'` is the same as `r'M{0,3}$` and, actually, accepts all strings,
since there is always an empty part at the end of the string:

    
    
    In [21]: pattern = r'M?M?M?$'
    
    In [22]: re.search(pattern, 'A string without capital m at all')
    Out[22]: <_sre.SRE_Match object; span=(33, 33), match=''>
    

