2010-12-29 13 views
1

html文字列のアンカーのhref値を抽出できました。今、私が達成したいのは、href値を抽出し、この値を新しいGUIDで置き換えることです。置き換えられたhtml文字列と抽出されたhref値のリストとそれに対応するGUIDの両方を返す必要があります。名前付きグループ正規表現の抽出と置き換え

ありがとうございます。

私の既存のコードは次のようである:

Dim sPattern As String = "<a[^>]*href\s*=\s*((\""(?<URL>[^\""]*)\"")|(\'(?<URL>[^\']*)\')|(?<URL>[^\s]*))" 

Dim matches As MatchCollection = Regex.Matches(html, sPattern, RegexOptions.IgnoreCase Or RegexOptions.IgnorePatternWhitespace) 

If Not IsNothing(matches) AndAlso matches.Count > 0 Then 
    Dim urls As List(Of String) = New List(Of String) 

    For Each m As Match In matches 
     urls.Add(m.Groups("URL").Value) 
    Next 
End If 

サンプルHTML文字列:

<html><body><a title="http://www.google.com" href="http://www.google.com">http://www.google.com</a><br /><a href="http://www.yahoo.com">http://www.yahoo.com</a><br /><a title="http://www.apple.com" href="http://www.apple.com">Apple</a></body></html> 

答えて

1

あなたはそのようなこと行うことができます:newHtmlは以下があり、最終的に

Dim pattern As String = "<a[^>]*href\s*=\s*((\""(?<URL>[^\""]*)\"")|(\'(?<URL>[^\']*)\')|(?<URL>[^\s]*))" 
Dim urls As New Dictionary(Of Guid, String) 
Dim evaluator As MatchEvaluator = Function(m) 
    Dim g As Guid = Guid.NewGuid() 
    Dim url = m.Groups("URL").Value 
    urls.Add(g, url) 
    Return m.Value.Replace(url, g.ToString()) 
End Function 

Dim newHtml = Regex.Replace(html, pattern, evaluator) 

を値:

<html><body><a title="329eb2c4-ee51-49fa-a8cd-2de319c3dbad" href="329eb2c4-ee51-49fa-a8cd-2de319c3dbad">http://www.google.com</a><br /><a href="77268e2d-87c4-443c-980c-9188e22f8496">http://www.yahoo.com</a><br /><a title="2941f77a-a143-4990-8ad7-3ef56972a8d4" href="2941f77a-a143-4990-8ad7-3ef56972a8d4">Apple</a></body></html> 

そしてurls辞書は次のエントリが含まれています。ところで

329eb2c4-ee51-49fa-a8cd-2de319c3dbad: http://www.google.com 
77268e2d-87c4-443c-980c-9188e22f8496: http://www.yahoo.com 
2941f77a-a143-4990-8ad7-3ef56972a8d4: http://www.apple.com 

は、regular expressions are not the best option for parsing HTMLは... HTML Agility Packのようなツールがより適切であろうことに注意してください。

+0

クラップス。事実の後に私はあなたの答えを複製したことに気づいただけです。 +1 :) –

関連する問題