本文介紹了正則表達(dá)式 VBA 匹配的處理方法,對大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
如何在第二個(gè) msgbox 中獲得值 81.16?正則表達(dá)式僅從字符串中獲取數(shù)值
How can i get the value 81.16 in second msgbox? 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 = "[d.]+"
End With
Set REMatches = RE.Execute(strData)
MsgBox REMatches(0)
MsgBox REMatches(1) 'getting error here
End Function
推薦答案
首先,盡量不要使用RegEx解析任何類型的xml.嘗試使用 xml 解析器或 XPath
XPath,XML 路徑語言,是一種用于選擇節(jié)點(diǎn)的查詢語言來自 XML 文檔.此外,XPath 可用于計(jì)算值(例如,字符串、數(shù)字或布爾值)來自 XML 的內(nèi)容文件.
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
進(jìn)入
.Global = True 'Matches all occurrences
如何在 VBA 中正確解析 XML:
請注意,我必須關(guān)閉您的 <br/>
標(biāo)記才能有效.
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
這篇關(guān)于正則表達(dá)式 VBA 匹配的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!