删除字符串开头的关键词,但不删除字符串中的所有关键词。

huangapple go评论66阅读模式
英文:

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 = &#39;d:\pictures\pictures\hallo\pictures\\&#39;
cleaned_path_name = re.sub(r&#39;^pictures\\&#39;, &#39;&#39;, re.sub(r&#39;^.:\\pictures\\&#39;, &#39;&#39;, 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&#39;^.:\\(pictures\\){1,2}&#39;, &#39;&#39;, 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&#39;\bpictures\\&#39;, &#39;&#39;, path_name, 1)
print(new_pathname)

d:\pictures\hallo\pictures\

huangapple
  • 本文由 发表于 2023年6月5日 23:25:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76407896.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定