[英]Understanding RegEx that finds multiline HTML comments
我在這里http://regexadvice.com/forums/thread/36397.aspx找到了RegEx,我正在尋找一種我不理解的行為的解釋。 RegEx應該找到不在腳本或樣式標簽內的多行HTML注釋。 我正在用它來構建一個可以在構建后剝離瀏覽器可訪問評論的應用程序。 例如找到這個
<!-- I am an ordinary comment
and I need two lines -->
但不是這個
<script language="javascript1.2">
<!--
function window_Onload()
{
alert('I am the on load event');
}
window.onload=window_Onload;
//-->
</script>
找到后,我可以刪除第一個評論塊,而忽略第二個。
以下模式可以完美地完成上述任務:
string multilinePattern = @"<!--((?!-->).)+-->(?>((?!</?(script|style)).)*)(?!</(script|style))";
match = Regex.Match(text, multilinePattern);
if (match.Success)
{
output.WriteLine("{0}", match.Value);
}
這段代碼將為我提供一個文件,其中不包含所有html注釋,而不會包含在腳本或樣式標簽中,但是它可以做其他我沒有得到的事情。
這是HTML的示例1和返回值:
HTML:
<!-- Outside Table -->
<table summary="<%= GetLocalResourceObject("LayoutTable.SummaryText") %>" cellspacing="0" cellpadding="0" border="0" width="650" align="center">
<tr>
<td class="tableHeader"> </td>
返回:
<!-- Outside Table -->
現在,這是HTML的示例2和返回值:
HTML:
<!-- Outside Table -->
<table summary="<%= GetLocalResourceObject("LayoutTable.SummaryText") %>" class="tabTableCell" cellpadding="0" cellspacing="0" width="750" align="center" >
<tr>
<td class="tableHeader"> </td>
返回:
<!-- Outside Table -->
<table summary="<%= GetLocalResourceObject("LayoutTable.SummaryText") %>" class="tabTableCell" cellpadding="0" cellspacing="0" width="750" align="center" >
<tr>
示例2是錯誤的示例:我不想在匹配結果中包含那部分html。 但是我可以看到的示例1和2之間的唯一區別是示例2中遵循“外部表”符號的額外換行符。
所以我的問題是,正則表達式中是什么導致匹配在示例2中一直包含html直到html標記。我需要更改什么才能使正則表達式與示例2相同來匹配示例2 1?
好的,這是使用HtmlAgilityPack可以完成的
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var comments = doc.DocumentNode
.Descendants()
.Where(d => d.Name == "#comment")
.Select(d => d.InnerText)
.ToList();
在我的測試中,在兩種情況下,它僅與注釋匹配。 但是,如果我指定“ Singleline
選項(您應該這樣做),則在兩種情況下它都將匹配整個shebang。 難道是您在第二項測試中以“ Singleline
模式進行比賽,而不是第一次進行?
但這仍然是一個不好的正則表達式。 注釋匹配后,原子組匹配並消耗不是SCRIPT或STYLE標記的任何內容(打開或關閉),然后先行斷言后面的內容不是SCRIPT或STYLE標記。
評論結束后,您不想消耗任何東西; 都應該是負面的前瞻。 例如:
(?inxs)
<!--((?!-->).)+-->
(?!
((?!</?(script|style)).)*
</(script|style)
)
(?inxs)
是內聯模式修飾符; 它接通IgnoreCase
, ExplicitCapture
, IgnorePatternWhitespace
,和Singleline
模式。 這又是一行,都是C#逐字字符串:
@"(?ins)<!--((?!-->).)+-->(?!((?!</?(script|style)).)*</(script|style))"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.