gpt4 book ai didi

regex - VBA 中的条件正则表达式

转载 作者:行者123 更新时间:2023-12-04 21:03:30 29 4
gpt4 key购买 nike

我在 Excel VBA 中使用 RegEx 解析多个 HTML 文件(我知道这不是最好的做法)但我有这种情况,它可以是 - 场景 1:

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

或者可能是 - 场景 2:
<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-2.12%如果类(class)以 success 结尾, 我要返回 +29253914.13%
我一直用于第二种情况并且工作正常的代码是:
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

关于regex - VBA 中的条件正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31013896/

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