0

(<h*></h*> and <a></a>)見出し(任意のサイズ)とアンカーhtmlタグの間、または属性としての内部タグの間にあることができない指定されたテキストをキャプチャする必要があるタスクがあります。

たとえば、私はテキストを持っています:

<h1>TfL</h1>
<a href="tfl.gov.uk">Tfl</a>
TfL is official organization for keeping London moving.

正規表現を使用して、これらのタグの外側でのみ「TfL」を照合することは可能ですか?

どうもありがとう。

ピーター。

4

2 に答える 2

1

この正規表現を試してください

(?<=<(h\d|a[^>].*?)>)(TfL)(?=</(h\d|a)>)

<h*></h*>およびからのすべてのTfLテキストを取得します<a></a>

于 2012-12-04T10:20:42.660 に答える
0

最終的に、HtmlAgilityPack.HtmlDocument.SelectNodes()を使用してノードを選択し、選択中のノードが除外タグであるかどうか、およびそのような親があるかどうかを(再帰的に)チェックしました。

Public Const cAlphabet As String = "AÁÄBCČDĎEÉĚFGHIÍJKLĹĽMNŇOÓÔPQRŔŘSŠTŤUÚŮVWXYÝZŽ0123456789" ' Accepted chars '

Dim nodes As HtmlNodeCollection = nothing
Dim doc As HtmlDocument = New HtmlDocument()

' div encapsulation is used for text which is not between any tags. '
' iHtmlText is variable which holds html document in text form '
doc.LoadHtml(String.Format("<div>{0}</div>", If(iHtmlText, String.Empty))) 

' "FIND_THIS_TEXT" can be any text which you want to find '
' Node selecting is case insensitive due to translate feature of xpath '
nodes = doc.DocumentNode.SelectNodes(
        String.Format("//*[contains(translate(text(), '{0}', '{1}'), '{2}')]",
                      cAlphabet, cAlphabet.ToLower, "FIND_THIS_TEXT".ToLower))

For Each node As HtmlNode In nodes
   If (IsNotOrNestedInSpecifiedNode(node, "a", "h1", "h2", "h3", "h4", "h5", "h6")) Then
       ' do something with the node here '
   End If
Next

上記のコードで使用されるIsNotOrNestedInSpecifiedNode関数:

Private Function IsNotOrNestedInSpecifiedNode(ByVal iNode As HtmlNode, ByVal ParamArray iExcludedHtmlTags() As String) As Boolean
        Dim ret As Boolean = False

        If (iNode.Name.IsIn(iExcludedHtmlTags)) Then
            ret = False
        ElseIf (iNode.ParentNode IsNot Nothing) Then
            ret = IsNotOrNestedInSpecifiedNode(iNode.ParentNode, iExcludedHtmlTags)
        Else
            ret = True
        End If

        Return ret
    End Function
于 2012-11-07T10:47:27.543 に答える