英文:
regex: remove keyword(s) at start but not in all of the string
问题
import re
path_name = 'd:\\pictures\\pictures\\hallo\\pictures\\'
cleaned_path_name = re.sub(r'(^|(?<=\\))pictures\\', '', path_name)
print(path_name)
print(cleaned_path_name)
d:\pictures\pictures\hallo\pictures\
hallo\pictures\
英文:
A path name starts with one or two times the same folder name pictures
. I need to remove these but keep any folders with the same name pictures
later in the path. I came up with this solution:
import re
path_name = 'd:\pictures\pictures\hallo\pictures\\'
cleaned_path_name = re.sub(r'^pictures\\', '', re.sub(r'^.:\\pictures\\', '', path_name))
print(path_name)
print(cleaned_path_name)
d:\pictures\pictures\hallo\pictures\
hallo\pictures\
Is there a way to do this in one regex expression?
答案1
得分: 2
"Limited repetition should work here:
cleaned_path_name = re.sub(r'^.:\(pictures\){1,2}', '', path_name)
{1,2} means that the expression beforehand occurs at minimum once and at maximum twice."
英文:
Limited repetition should work here:
cleaned_path_name = re.sub(r'^.:\\(pictures\\){1,2}', '', path_name)
{1,2} means that the expression beforehand occurs at minimum once and at maximum twice.
答案2
得分: 0
使用 re.subn
限制替换的次数:
new_pathname, _ = re.subn(r'\bpictures\\', '', path_name, 1)
print(new_pathname)
d:\pictures\hallo\pictures\
英文:
Use re.subn
to limit the number of substitutions:
new_pathname, _ = re.subn(r'\bpictures\\', '', path_name, 1)
print(new_pathname)
d:\pictures\hallo\pictures\
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论