2

如何在第二个 msgbox 中获得值 81.16? 正则表达式仅从字符串中获取数值

Sub Tests()
    Const strTest As String = "<td align=""right"">116.83<span class=""up2""></span><br>81.16<span class=""dn2""></span></td>"
    RE6 strTest
End Sub



Function RE6(strData As String) As String
    Dim RE As Object, REMatches As Object

    Set RE = CreateObject("vbscript.regexp")
    With RE
        ' .MultiLine = True
        '.Global = False
        .Pattern = "\b[\d.]+\b"
    End With

    Set REMatches = RE.Execute(strData)
    MsgBox REMatches(0)
    MsgBox REMatches(1)    'getting error here
End Function
4

1 回答 1

8

首先,尽量不要使用 RegEx 来解析任何类型的 xml。尝试使用 xml 解析器或 XPath

XPath,即 XML 路径语言,是一种用于从 XML 文档中选择节点的查询语言。此外,XPath 可用于从 XML 文档的内容计算值(例如,字符串、数字或布尔值)。

解决你的问题改变

'.Global = False 'Matches only first occurrence

进入

.Global = True 'Matches all occurrences

如何在 VBA 中正确解析 XML:

请注意,我必须关闭您的<br />标签才能生效。

Private Sub XmlTestSub()
On Error GoTo ErrorHandler

    Dim xml As MSXML2.DOMDocument60
    Dim nodes As MSXML2.IXMLDOMNodeList
    Dim node As MSXML2.IXMLDOMNode

    yourXmlString = "<td align=""right"">116.83<span class=""up2""></span><br />81.16<span class=""dn2""></span></td>"

    Set xml = New MSXML2.DOMDocument60
    If (Not xml.LoadXML(yourXmlString)) Then
        Err.Raise xml.parseError.ErrorCode, "XmlTestSub", xml.parseError.reason
    End If

    Set nodes = xml.SelectNodes("/td/text()") 'XPath Query

    For Each node In nodes
        Debug.Print node.NodeValue
    Next node

Done:
    Exit Sub

ErrorHandler:
    MsgBox Err.Number & " " & Err.Description, vbCritical
    Resume Done

End Sub
于 2013-04-06T08:45:05.690 回答