San*_*osh 2 html regex vba excel-vba xml-parsing
如何在第二个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
Run Code Online (Sandbox Code Playgroud)
首先,尽量不要使用RegEx来解析任何类型的xml.尝试使用xml解析器或 XPath
XPath是XML Path Language,是一种用于从XML文档中选择节点的查询语言.另外,XPath可用于从XML文档的内容计算值(例如,字符串,数字或布尔值).
'.Global = False 'Matches only first occurrence
Run Code Online (Sandbox Code Playgroud)
成
.Global = True 'Matches all occurrences
Run Code Online (Sandbox Code Playgroud)
请注意,我必须关闭您的<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
Run Code Online (Sandbox Code Playgroud)