gpt4 book ai didi

html - 正则表达式 VBA 匹配

转载 作者:太空宇宙 更新时间:2023-11-04 14:04:40 25 4
gpt4 key购买 nike

如何在第二个 msgbox 中获取值 81.16? Regex get only numeric values from string

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

最佳答案

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

XPath, the XML Path Language, is a query language for selecting nodes from an XML document. In addition, XPath may be used to compute values (e.g., strings, numbers, or Boolean values) from the content of an XML document.

为了解决你的问题而改变

'.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

关于html - 正则表达式 VBA 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15848486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com