嘿大家, 我在另一个编码冒险。我今天早些时候开始自学了一些基本的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