Why does re.sub('.*?', '-', 'abc') return '-a-b-c-' instead of '-------'?
Question: This is the results from python2.7.

    
    
    >>> re.sub('.*?', '-', 'abc')
    '-a-b-c-'
    

The results I thought **should** be as follows.

    
    
    >>> re.sub('.*?', '-', 'abc')
    '-------'
    

But it's not. Why?


Answer: Are you sure you interpreted
[re.sub](https://docs.python.org/2/library/re.html)'s documentation correctly?

> `*?`, `+?`, `??` The '_', '+', and '?' qualifiers are all greedy; they match
> as much text as possible. Sometimes this behaviour isn’t desired; if the RE
> <._> is matched against `'<H1>title</H1>'`, it will match the entire string,
> and not just `'<H1>'`. Adding '?' after the qualifier makes it perform the
> match in non-greedy or minimal fashion; as few characters as possible will
> be matched. Using .*? in the previous expression will match only ''.

Adding a `?` will turn the expression into a non-greedy one.

**Greedy:**

    
    
    re.sub(".*", "-", "abc")
    

**non-Greedy:**

    
    
    re.sub(".*?", "-", "abc")
    

**Update:** FWIW `re.sub` does exactly what it should:

    
    
    >>> from re import sub
    >>> sub(".*?", "-", "abc")
    '-a-b-c-'
    >>> sub(".*", "-", "abc")
    '-'
    

See @BrenBarn's awesome answer on why you get `-a-b-c-` :)

Here's a visual representation of what's going on:

    
    
    .*?
    

![Regular expression
visualization](https://www.debuggex.com/i/mOJU8zu1w1xkDvdT.png)

[Debuggex Demo](https://www.debuggex.com/r/mOJU8zu1w1xkDvdT)

