0

我有一个任务,我应该捕获指定的文本,这些文本不能在标题(任何大小)和锚 html 标签之间,(<h*></h*> and <a></a>)也不能在标签内作为属性。

例如我有文字:

<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 回答