我有一個基本的錨節點作爲字符串,並希望從中獲取URL和文本。例如:從vbnet的html節點獲取數據
<a href="http://MyAwesomeWebsite.com/">Go to MyAwesomeWebsite</a>
我想兩個字符串,一個具有:
http://MyAwesomeWebsite.com/
和其他與
MyAwesomeWebsite
如何代碼呢?
我有一個基本的錨節點作爲字符串,並希望從中獲取URL和文本。例如:從vbnet的html節點獲取數據
<a href="http://MyAwesomeWebsite.com/">Go to MyAwesomeWebsite</a>
我想兩個字符串,一個具有:
http://MyAwesomeWebsite.com/
和其他與
MyAwesomeWebsite
如何代碼呢?
你可以使用正則表達式來提取要作爲旁的文字:
Imports System.Text.RegularExpressions
Sub Main()
Dim anchor As String
anchor = "<a href=""http://MyAwesomeWebsite.com/"">Go to MyAwesomeWebsite</a>"
Dim href As String = Regex.Match(anchor, "\""[a-z,A-Z,0-9,:,/,.]+\""").Value
Console.WriteLine(href.Substring(1, href.Length - 2))
Dim content As String = Regex.Match(anchor, "\>[a-z,A-Z,0-9,:,/,., ]+\<").Value
Console.WriteLine(content.Substring(1, content.Length - 2))
Console.ReadKey()
End Sub
您也可以使用由字符串提供的方法,如的IndexOf和子字符串。 但是如果你想解析很多人認爲我建議你使用像HtmlAgilePack這樣的庫。
Html Agility Pack庫可以爲您解析字符串並返回所需的任何信息。這裏是關於如何使用它的stackoverflow上的plenty of related questions。
另一種方法涉及使用regular expression查找匹配所需模式的子字符串。
謝謝!但有時鏈接包含一個'rel'屬性,它將作爲超級引用出現。任何簡單的修復正則表達式?或者我應該使用圖書館。我試圖避免只爲一個小任務使用一個庫。 – 2012-04-15 03:17:50
如果你的目標是檢查'rel'頁面是更好的使用庫。但是如果你只是想獲得'rel'的值,你可以使用另一個正則表達式作爲下一個:'Dim rel As String = Regex.Match(anchor ,「rel = \」「[az,AZ,0-9,:,/ ,.] + \」「」)值 Console.WriteLine(rel.Substring(5,rel.Length - 6)) '如果你想在使用它之前檢查正則表達式是否匹配(對於'href'或'rel'使用正則表達式之間的區別),你可以使用** Regex.IsMatch **。我希望能幫到你;) – 2012-04-16 01:01:31