在將檔案轉換為 rST 之前,我正在用 Python 撰寫一個自動化腳本來遍歷舊的 HTML 檔案檔案并運行一些 RegEx 命令。我在嘗試將某些模式包裝在標簽<pre>中時遇到了障礙。</pre>
我需要找到以下 HTML 模式的每個組出現,并在<pre>之前插入一個標簽,在</pre>之后插入一個標簽。
圖案:
- 類名為“CodeReference”的 p 標簽,重復 1 次或多次
<p >
示例 HTML:
<h3>
Could be any HTML here
</h3>
<p class="CodeReference">
First line</p>
<p class="CodeReference">
Second line</p>
<p class="CodeReference">
Last line</p>
<div>
More random HTML down here as well
</div>
期望的結果:
<h3>
Could be any HTML here
</h3>
<pre>
<p class="CodeReference">
First line of code</p>
<p class="CodeReference">
Second line of code</p>
<p class="CodeReference">
Last line of code</p>
</pre>
<div>
More random HTML down here as well
</div>
我目前的挑戰是沒有先前的模式來參考積極的后視,所以我需要捕獲每組<p >模式并將整個組包裝在<pre></pre>標簽中。
換句話說,<p >我需要在每組中找到第一個出現并<pre>在其前面插入一個標簽。然后,在每組 中<p >,找到最后一次出現并</pre>在其后插入一個標簽。
這是我迄今為止嘗試過的(使用 Python):Regex101 作業區
code_block = re.sub(r'(?<!(<\/p>\n))<p class=\"CodeReference\">', r'<pre>\g<0>', code_block)
^基于它前面沒有結束</p>標記來捕獲第一個匹配項。然而,這并沒有捕捉到最后一次發生的事情,感覺就像我做錯了。我對多個 RegEx 陳述句持開放態度,不需要是單行的。我只是不知道如何正確捕獲這組段落標簽并參考第一次和最后一次出現。
任何幫助將不勝感激,謝謝!
uj5u.com熱心網友回復:
為了獲得最佳結果,您可能需要使用 Python 的 Beautiful Soup 庫進行調查。如果您必須使用正則運算式,并且假設您沒有任何嵌套的 HTML 標簽,您可以嘗試以下方法:
inp = """<h3>
Could be any HTML here
</h3>
<p >
First line</p>
<p >
Second line</p>
<p >
Last line</p>
<div>
More random HTML down here as well
</div>"""
output = re.sub(r'((?:<p >.*?</p>\s*) )', r'\n<pre>\n\n\1</pre>\n\n', inp, flags=re.S)
print(output)
這列印:
<h3>
Could be any HTML here
</h3>
<pre>
<p class="CodeReference">
First line</p>
<p class="CodeReference">
Second line</p>
<p class="CodeReference">
Last line</p>
</pre>
<div>
More random HTML down here as well
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/420682.html
標籤:
