![](/img/trans.png)
[英]Is there a way to use regular expressions in the replacement string in re.sub() in Python?
[英]Photo folder string replacement Regular Expressions python
我想替換
text = '2012-02-23 | My Photo Folder'
同
new_text = '20120223_MyPhotoFolder'
我找到了一個與我的日期格式匹配的正則表達式http://regexlib.com/RETester.aspx?regexp_id=933
什么是最好的方法來解決這個問題? 我是否需要正則表達式組,然后在這些組中進行替換?
我假設我可以簡單地搜索“|”並用普通的string.replace()替換為“_和” - “with”,但我想找到一個更通用的解決方案。
提前致謝。
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')
以刪除空格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.