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,' ')))
输出:
>>>
20120223_MyPhotoFolder
一点解释:
re.VERBOSE
让我们在多行中编写正则表达式,使其更具可读性并允许注释。
'{}{}{}_{}'.format
只是一种字符串插值方法,它将参数放在{}
.
translate
方法应用于result.group('name_with_spaces')
删除空格。