VBA中的条件正则expression式

我在Excel VBA中使用RegExparsing多个HTML文件(我知道不是最好的事情),但我有这种情况可以是 – scheme1:

<span class="big vc vc_2 "><strong><i class="icon icon-angle-circled-down text-danger"></i>&pound;51,038</strong> <span class="small">(-2.12%)</span></span> 

或者可能是 – scheme2:

 <span class="big vc vc_2 "><strong><i class="icon icon-angle-circled-up text-success"></i>&pound;292,539</strong> <span class="small">(14.13%)</span></span> 

如果class级结束danger ,我想返回-51038-51038 -2.12%如果class级success ,我想返回+29253914.13%

我已经用于第二种scheme,并正常工作的代码是:

 Sub Test() With CreateObject("VBScript.RegExp") .Global = True .MultiLine = True .IgnoreCase = False .Pattern = "<i class=""icon icon-angle-circled-up text-success""></i>([\s\S]*?)<" sValue = HtmlSpecialCharsDecode(.Execute(sContent).Item(0).SubMatches(0)) End With sValue = CleanString(sValue) End sub Function HtmlSpecialCharsDecode(sText) With CreateObject("htmlfile") .Open With .createElement("textarea") .innerHTML = sText HtmlSpecialCharsDecode = .Value End With End With End Function Function CleanString(strIn As String) As String Dim objRegex Set objRegex = CreateObject("vbscript.regexp") With objRegex .Global = True .Pattern = "[^\d]+" CleanString = .Replace(strIn, vbNullString) End With End Function 

所有你需要做的就是添加一些更多的“或”条件的捕获组。 在你的情况下,你想要组(success|danger) (也(up|down)基于示例)。 然后,而不是只检查唯一的子匹配,检查你放在你的模式中的条件:

 Dim regex As Object Dim matches As Object Dim expr As String expr = "<i class=""icon icon-angle-circled-(up|down) text-(success|danger)""></i>(.*?)</.*\((.*)%\)<.*" Set regex = CreateObject("VBScript.RegExp") With regex .Global = True .MultiLine = True .IgnoreCase = False .Pattern = expr Set matches = .Execute(sContent) End With Dim isDanger As Boolean If matches.Count > 0 Then isDanger = (HtmlSpecialCharsDecode(matches.item(0).SubMatches(1)) = "danger") sValue1 = HtmlSpecialCharsDecode(matches.item(0).SubMatches(2)) sValue2 = HtmlSpecialCharsDecode(matches.item(0).SubMatches(3)) End If If isDanger Then 'Was "danger" Debug.Print -CLng(CleanString(sValue1)) Debug.Print -CDbl(sValue2) Else 'Was "success" Debug.Print CLng(CleanString(sValue1)) Debug.Print CDbl(sValue2) End If