【问题标题】:Photo folder string replacement Regular Expressions python照片文件夹字符串替换正则表达式python
【发布时间】:2013-04-02 14:02:38
【问题描述】:

我想更换

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

new_text = '20120223_MyPhotoFolder'

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

解决这个问题的最佳方法是什么? 我是否需要正则表达式组,然后在这些组中进行替换?

我假设我可以简单地搜索“|”并用普通 string.replace() 替换为“_”和“-”,但我想找到一个更通用的解决方案。

提前致谢。

【问题讨论】:

  • 如果您描述了您想要涵盖的一般情况,我们只能为您提供“更一般的解决方案”。
  • 假设我在字符串的其他地方遇到了“|”。如果它正好在日期之后,我只想用“_”替换它。 “2012-02-23”->“20120223”也是如此。我只想替换 "-" --> "" 如果它出现在字符串的日期部分中。

标签: python regex string replace


【解决方案1】:
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 让我们可以在多行中编写正则表达式,使其更具可读性,并且还允许 cmets。

'{}{}{}_{}'.format 只是一种字符串插值方法,它将参数放在{} 指定的位置。

translate 方法应用于result.group('name_with_spaces') 以删除空格。

【讨论】:

  • 太棒了!非常感谢!我只是想问这个。这正是我需要做的。我唯一添加的是一个 if 语句,检查结果是真还是假,因为目录列表可能包含我不想碰的东西。
猜你喜欢
  • 2022-11-07
  • 2013-06-13
  • 2018-07-13
  • 1970-01-01
  • 2017-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多