[英]Python Regex replace multiple occurencies of parts of a string
我有一大堆HTML,包含多個<img>
標簽。 標簽的當前格式是:
<img width="580" height="183" src="/images/stories/acidalkalinetable.jpg" alt="acid alkaline table" title="Body pH Balance">
我想通過html和每個<img>
標簽將格式更改為:
<img width="580" height="183" src="{{media url="wysiwyg/acidalkalinetable.jpg"}}" alt="acid alkaline table" title="Body pH Balance">
你可以看到它正在變化的src
。 我保留了文件名但改變了src
其他部分
如果img是單個字符串,我可以做類似的事情:
content = '<img width="580" height="183" src="/images/stories/acidalkalinetable.jpg" alt="acid alkaline table" title="Body pH Balance">'
filename = re.search(r'/images/stories/\w+\.(jpg|png|gif)', content)
new_content = re.sub(r'/images/stories/\w+\.(jpg|png|gif)', '{{media url="wysiwyg/' + filename + '"}}', content)
(我沒有測試過)
但我不確定如何在HTML中每次出現<img>
標簽時都這樣做
您需要將文件名捕獲為一個組,然后您可以一次性替換它:
re.sub(r'/images/stories/([\w%]+\.(?:jpg|png|gif))', r'{{media url="wysiwyg/\1"}}', content)
這會將捕獲組( (...)
)放在整個文件名的周圍,包括擴展名(現在本身使用非捕獲(?:...)
組),從而導致:
>>> re.sub(r'/images/stories/([\w%]+\.(?:jpg|png|gif))', r'{{media url="wysiwyg/\1"}}', content)
'<img width="580" height="183" src="{{media url="wysiwyg/acidalkalinetable.jpg"}}" alt="acid alkaline table" title="Body pH Balance">'
這使用\\1
作為替換模式,請參閱re.sub()
文檔 。
此re.sub()
調用將使用{{media url="wisywig/.."}}
語法替換所有匹配/images/stories/..
路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.