Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
照片文件夹字符串替换正则表达式python_Python_Regex_String_Replace - Fatal编程技术网

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

照片文件夹字符串替换正则表达式python,python,regex,string,replace,Python,Regex,String,Replace,我想换一个 text = '2012-02-23 | My Photo Folder' 与 我在这里找到了一个与我的日期格式匹配的正则表达式 最好的方法是什么? 我是否需要正则表达式组,然后在这些组中进行替换 我假设我可以简单地搜索“|”,并用普通字符串替换为“u”,用“”替换为“-”,但我想找到一个更通用的解决方案 提前谢谢 import re text = '2012-02-23 | My Photo Folder' pattern = r''' (?P<year>\d{

我想换一个

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

我在这里找到了一个与我的日期格式匹配的正则表达式

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

我假设我可以简单地搜索“|”,并用普通字符串替换为“u”,用“”替换为“-”,但我想找到一个更通用的解决方案

提前谢谢

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,' ')))

一点解释: 让我们在多行中编写正则表达式,使其更具可读性,并允许注释

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


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

如果您描述希望涵盖的一般情况,我们只能为您提供“更一般的解决方案”。假设我在字符串中的其他地方遇到“|”。如果它正好在日期之后,我只想用“|”替换它。对于2012-02-23”->“20120223”。我只想替换“-”->”“如果它发生在字符串的日期部分。太好了!谢谢!我只是想问问这件事。这正是我需要做的。我只添加了一个if语句来检查结果是真是假,因为目录列表中可能有我不想碰的东西。
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