簡體   English   中英

正則表達式匹配URL(如果不在HTML注釋行中)

[英]Regex match URL if not in html comment line

我只想匹配“ https://www.mysite/embed/M7znk1c-ay0 ”,除非它不是html注釋。

所以不要匹配這條線

<!--<p><iframe src="https://www.mysite/embed/M7znk1c-ay0" width="854" height="480" frameborder="0" allowfullscreen="allowfullscreen"></iframe>-->

但匹配這條線

<article class="art-post"><div class="art-postcontent clearfix"><div class="art-article"><p><iframe  src="https://www.mysite/embed/M7znk1c-ay0" ></iframe></p>

我嘗試過這種模式^(?=<!--).*www.mysite\\/embed\\/+[\\w\\-]*

但是效果不佳

您幾乎正確地做到了。 正確的正則表達式為^(?!<!--).*"(.*www.mysite\\/embed\\/+[\\w\\-]*)

HTML不是常規的,因此使用正則表達式解析html可能不是一個好主意... @csabinho的答案^(?!<!--).*"(.*www.mysite\\/embed\\/+[\\w\\-]*)如果您要匹配的URL位於頁面中間,則不會起作用,它只是檢查行是否不以注釋開頭。

最佳實踐是創建DOM並使用XPath查詢類似XML的內容。

編輯:

順便說一句,您可以先使用以下代碼刪除注釋。

System.Text.RegularExpressions;
...
string pattern = @"(<!--(.+?)-->)";
var res = Regex.Replace(input, pattern, "", RegexOptions.Singleline);

然后使用簡單的模式從結果中提取URL

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM