You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用单个正则表达式移除路径开头的pictures文件夹(保留后续同名)

单个正则表达式实现方案

当然可以用单个正则表达式完成这个需求,核心思路是匹配路径开头可选的盘符+1-2次连续的pictures\,直接将这部分替换为空即可。

实现代码

import re
# 使用原始字符串标记r,避免转义字符解析问题
path_name = r'd:\pictures\pictures\hallo\pictures\\'
# 单个正则完成替换
cleaned_path_name = re.sub(r'^([a-zA-Z]:\\)?(pictures\\){1,2}', '', path_name)
print(path_name)
print(cleaned_path_name)

输出结果

d:\pictures\pictures\hallo\pictures\
hallo\pictures\

正则表达式说明

  • ^:锚定字符串起始位置,确保只匹配路径开头的目标内容
  • ([a-zA-Z]:\\)?:匹配可选的盘符前缀(如d:\),?表示该部分可出现0次或1次,兼容不带盘符的路径场景
  • (pictures\\){1,2}:匹配连续1到2次的pictures\,精准对应需要移除的开头文件夹

内容的提问来源于stack exchange,提问作者Bruno Vermeulen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 14:57:12