[英]Python regex replace and use match
我有一個文本,我想將所有附件:ATT000xx文件替換為另一個鏈接/dwl/attachment/ATT000xx
regex = "attachment:ATT\d+"
txt = "<img src=\"attachment:ATT00001\""
x = re.sub("attachment:ATT\d+", "/dwl/attachment/", txt)
我怎樣才能找到最后一個數字(00001/00002)並把行尾
在 nodejs 中它將是
.replace(/attachment:([a-f0-9]+)\/(ATT\d+)/g, (str, mid, aid) =>
援助是我尋找的 nodejs
對 ATT + 數字項使用捕獲組:
txt = "<img src=\"attachment:ATT00001\">"
output = re.sub(r'attachment:(ATT\d+)', r'/dwl/attachment/\1', txt)
print(output) # <img src="/dwl/attachment/ATT00001">
如果我沒理解錯的話,你只需要匹配你想更換的部分。 為此,您可以使用積極的前瞻:
regex = "attachment:ATT(?=\d+)"
txt = "<img src=\"attachment:ATT00001\""
x = re.sub(regex, "/dwl/attachment/", txt)
print(x)
這將匹配任何后跟一位或多位數字的attachment:ATT
,但不會匹配這些數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.