仅在指定的html标记之外匹配指定的文本

时间:2012-10-09 14:34:25

标签: regex

我有一个任务,我应该捕获指定的文本,不能在标题(任何大小)和锚点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”?

非常感谢。

彼得。

2 个答案:

答案 0 :(得分:1)

试试这个正则表达式

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

它将从<h*></h*><a></a>

中获取所有TfL文字

答案 1 :(得分: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