Photo folder string replacement Regular Expressions python
Question: I would like to replace

    
    
    text = '2012-02-23 | My Photo Folder'
    

with

    
    
    new_text = '20120223_MyPhotoFolder'
    

I found a regular expression that matches my date format here
<http://regexlib.com/RETester.aspx?regexp_id=933>

what is the best way to approach this? Do I need regular expression groups and
then do the replacement in those groups?

I assume I could simply search for " | " and replace with "_ and "-" with "" by normal string.replace(), but I would like to find a more general solution.

Thanks in advance.


Answer: 
    import re
    
    text = '2012-02-23 | My Photo Folder'
    
    pattern = r'''
    (?P<year>\d{4}) # year group consisting of 4 digits
    -
    (?P<month>\d{2}) # month group consisting of 2 digits
    -
    (?P<date>\d{2}) # date group consisting of 2 digits
    \s\|\s
    (?P<name_with_spaces>.*$) # name_with_spaces consuming the rest of the string to the end
    '''
    compiled = re.compile(pattern, re.VERBOSE)
    result = compiled.match(text)
    print('{}{}{}_{}'.format(
        result.group('year'),
        result.group('month'),
        result.group('date'),
        result.group('name_with_spaces').translate(None,' ')))
    

Output:

    
    
    >>> 
    20120223_MyPhotoFolder
    

* * *

### A little explanation:

[`re.VERBOSE`](http://docs.python.org/2/library/re.html#re.VERBOSE) lets us
write regular expression in multiple lines making it more readable and also
allows comments.

[`'{}{}{}_{}'.format`](http://docs.python.org/2/library/string.html#format-
examples) is just a string interpolation method which puts arguments in the
places specified by `{}`.

[`translate`](http://docs.python.org/2/library/string.html#string.translate)
method is applied to `result.group('name_with_spaces')` to remove spaces.

