只有在語法不正確且沒有其他庫可以處理的情況下,您才應該使用正則表達式來操縱HTML。
隨着HtmlAgilityPack(安裝NuGet包),你可以很容易地得到所有a
標籤,並從中取出title
屬性是這樣的:
Dim s = "<img title=""3497fh-39848f-04ghk38-483728_part1__book1_93822-3948329928"">"
Dim doc As HtmlDocument = New HtmlDocument()
doc.LoadHtml(s)
RemoveAttributeFromTag(doc, "title")
Debug.Print(doc.DocumentNode.OuterHtml)
與RemoveAttributeFromTag
之中:
Private Sub RemoveAttributeFromTag(html As HtmlDocument, AttName As String)
Dim elements = html.DocumentNode.SelectNodes("//@" + AttName)
For Each element In elements
element.Attributes.Remove(AttName)
Next
End Sub
這版畫<img>
:
最後的意思度假村的解決方案是
Regex.Replace(str, "(?<=<[_a-zA-Z][^<]*?)\s+style=""[^""]*""", "")
其中
(?<=<[_a-zA-Z][^<]*?)
- 積極的回顧後,確保/要求立即到當前位置的左邊,有<
,然後ASCII字母或_
後面加上任意0比<
等,儘可能少+字符,可以發現
\s+
- 1+空格
style="
- 字面style="
子
[^"]*
- 0+比"
"
其他字符 - 最終"
見regex demo。
您確定不想使用HTML解析器來解析HTML嗎? https://www.nuget.org/packages/HtmlAgilityPack – Ryan
@Ryan我其實已經安裝了。這將如何更容易地刪除標題屬性?謝謝 – SkyeBoniwell
所以你想刪除標題標籤和其中的所有內容嗎? – Codexer