嘿大家, 我在另一個編碼冒險。我今天早些時候開始自學了一些基本的RegEx,並且創建了一個C#應用程序,它輸入一個HTML文件和一個RegExes列表框,然後使用這些RegEx來替換或刪除HTML標籤。 我設法使一些正常工作的RegExes清理並移除亂拋垃圾表的標籤,但我還需要刪除硬編碼css樣式的混亂,並將其替換爲對外部參考的引用。 經過大量的試驗和錯誤,我終於想出了一些從<style type="text/css">
到</style>
中選擇的東西,但由於某種原因,它完全跳過了單獨的樣式標籤塊。儘管如此,它在最後一個結束時停止。 這是一個比需要的信息更好奇,這應該現在工作正常,因爲我可以將與單一<link>
相匹配的內容替換爲外部CSS。 截至目前,我正則表達式是這樣的:RegEx匹配的HTML風格標籤打開,內容和關閉
<style((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)>(.*?\r\n)*(</style>)
上半年從here拍攝,中間位是我奮鬥最有,因爲我已經忘記了\ r \ n和當然的了關閉標籤是逐字的。
就像我說的,這工作得很好,我唯一的疑慮是,這種代碼:
<style type="text/css">
<!--
#wrapper #content #main2col .modbox tr td {
color: #3366cc;
border-top-style: solid;
border-right-style: solid;
border-bottom-style: solid;
border-left-style: solid;
}
#wrapper #content #main2col .modbox tr td p em {
color: #0a304e;
}
#wrapper #content #main2col .modbox tr td em br {
color: #0a304e;
}
#wrapper #content #main2col .modbox tr td em strong {
color: #0a304e;
}
#wrapper #content #main2col p strong {
color: #0a304e;
}
#wrapper #content #main2col table tr td strong {
color: #0a304e;
}
-->
</style>
<style type="text/css">
<!--
table.modbox {
font-size:9pt;
font-HCMmily:"Calibri", "sans-serif";
border-top-style: solid;
border-right-style: solid;
}
p.modbox {
margin-top:0in;
margin-right:0in;
margin-bottom:10.0pt;
margin-left:0in;
line-height:normal;
font-size:11.0pt;
font-HCMmily:"Calibri", "sans-serif";
}
#wrapper #content #main2col .modbox tr .modbox {
color: #09C;
font-style: normal;
}
#wrapper #content #main2col .modbox {
color: #3366cc;
}
#wrapper #content #main2col .modbox {
color: #3a5774;
}
#wrapper #content #main2col .modbox tr .modbox .MsoNormal .modbox {
color: #3a5774;
}
#wrapper #content #main2col .modbox {
color: #3a5774;
}
-->
</style>
<style type="text/css">
<!--
table.MsoTableGrid {
border:solid;
font-size:11.0pt;
font-HCMmily:"Calibri", "sans-serif";
}
p.MsoNormal {
margin-top:0in;
margin-right:0in;
margin-bottom:5pt;
margin-left:0in;
line-height:normal;
font-size:10pt;
font-HCMmily:"Calibri", "sans-serif";
}
-->
</style>
<style type="text/css">
<!--
table.modbox {
font-size:10.0pt;
font-family:"Times New Roman","serif";
}
-->
</style>
只有一個匹配,返回。我想弄清楚爲什麼它沒有抓住</style>
的拳頭關閉標籤。爲了記錄,我嘗試添加(\ r \ n)?關閉標籤位後,但沒有任何區別。
今天是我第一次與RegEx合作,所以我真的很陌生,我可能會犯一個非常簡單的錯誤。
任何人都可以解釋我做錯了什麼嗎?任何援助非常感謝!
HTML與正則表達式解析通常是不好的主意:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Alex 2011-04-23 08:03:30
有上面的正則表達式的第二個問題:閉合樣式標籤永遠不會匹配。它必須是(<[/]style>)匹配反斜槓! – sebilasse 2017-04-07 09:54:52
不要對HTML標籤使用正則表達式!使用解析器代替... – c24b 2017-10-30 15:53:45