Python regular expression to change date formatting
Question: I have an array of strings representing dates like '2015-6-03' and I want to
convert these to the format '2015-06-03'.

Instead of doing the replacement with an ugly loop, I'd like to use a regular
expression. Something along the lines of:

    
    
    str.replace('(-){1}(\d){1}(-){1}', '-0{my digit here}-')
    

Is something like this possible?


Answer: You don't have to retrieve the digit from the match. You can replace the
hyphen before a single-digit month with `-0`.

Like this:

    
    
    re.sub('-(?=\d-)', '-0', text)
    

Note that `(?=\d-)` is a non-capturing expression because the opening
parenthesis is followed by the special sequence `?=`. That's why only the
hyphen gets replaced.

Test:

    
    
    import re
    text = '2015-09-03  2015-6-03  2015-1-03 2015-10-03'
    re.sub('-(?=\d-)', '-0', text)
    

Result:

    
    
    '2015-09-03  2015-06-03  2015-01-03 2015-10-03'
    

