照片文件夹字符串替换正则表达式python

2024-06-16 13:05:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想替换

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

new_text = '20120223_MyPhotoFolder'

我在这里找到了一个与我的日期格式匹配的正则表达式 http://regexlib.com/RETester.aspx?regexp_id=933

最好的方法是什么? 我是否需要正则表达式组,然后在这些组中进行替换?你知道吗

我假设我可以简单地搜索“|”,然后用“|”和“-”替换为“正常”字符串.替换(),但我想找到一个更普遍的解决办法。你知道吗

提前谢谢。你知道吗


Tags: 方法textcomidhttpnewmy格式
1条回答
网友
1楼 · 发布于 2024-06-16 13:05:45
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

一点解释:

^{}允许我们在多行中编写正则表达式,使其更具可读性,还允许注释。你知道吗

^{}只是一个字符串插值方法,它将参数放在{}指定的位置。你知道吗

^{}方法应用于result.group('name_with_spaces')以移除空格。你知道吗

相关问题 更多 >