Why this regular expression pattern matches even an extra character in string?
Question: It is becoming hard for me to learn regular expressions, see the following
python regular expression code snippet.

    
    
    >>> import re
    >>> str = "demo"
    >>> re.search("d?mo",str)
    <_sre.SRE_Match object at 0x00B65330>
    

In the above example, why it is returning the matching object, even it is not?

I know, symbol '?' means it will match either 0 or 1 repetitions of the
preceding character, but

From the above example,

    
    
    1.'d' is matched with 'd'
    2.'m' is matched with 'm'
    3.'o' is matched with 'o'
    

But with which character 'e' is matched? Accoding to my understanding, only
'dmo' or 'mo' have to be matched with the given pattern, but why 'demo'.

If I want to match only 'dmo' or 'mo', what is the correct pattern?


Answer: `re.search('R', str)` is effectively the same as `re.match('.*R', str)` for
regexes `R`.

So you have (effectively... ignoring newlines)

    
    
    re.match(".*d?mo", "demo")
    

where the `.*` matches `"de"`, the `d?` matches `""` and the `mo` matches
`"mo"`.

* * *

You can check this with a capturing group:

    
    
    re.search("(d?mo)", "demo").group(0)
    #>>> 'mo'
    

The `d?` matches nothing, as it's optional.

