正则表达式VBA比赛 [英] Regex VBA Match

查看:136
本文介绍了正则表达式VBA比赛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 = "\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

First of all, try not to use RegEx to parse any kind of xml. Try using xml parsers or XPath


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

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.



解决您的问题更改



To solve your problem change

'.Global = False 'Matches only first occurrence

进入

.Global = True 'Matches all occurrences



如何在VBA中正确解析XML: h2>

请注意,我不得不关闭您的< 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

这篇关于正则表达式VBA比赛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆