gpt4 book ai didi

regex - 在 VBA 中对数学(中缀)表达式进行标记

转载 作者:行者123 更新时间:2023-12-02 21:09:50 28 4
gpt4 key购买 nike

我需要使用 VBA 对数学表达式进行标记。我有一个可行的解决方案,但正在寻找一种更有效的方法(可能是 RegExp)。

我当前的解决方案:

Function TokeniseTheString(str As String) As String()

Dim Operators() As String
' Array of Operators:
Operators = Split("+,-,/,*,^,<=,>=,<,>,=", ",")

' add special characters around all "(", ")" and ","
str = Replace(str, "(", Chr(1) & "(" & Chr(1))
str = Replace(str, ")", Chr(1) & ")" & Chr(1))
str = Replace(str, ",", Chr(1) & "," & Chr(1))

Dim i As Long
' add special characters around all operators
For i = LBound(Operators) To UBound(Operators)
str = Replace(str, Operators(i), Chr(1) & Operators(i) & Chr(1))
Next i

' for <= and >=, there will now be two special characters between them instead of being one token
' to change < = back to <=, for example
For i = LBound(Operators) To UBound(Operators)
If Len(Operators(i)) = 2 Then
str = Replace(str, Left(Operators(i), 1) & Chr(1) & Chr(1) & Right(Operators(i), 1), Operators(i))
End If
Next i

' if there was a "(", ")", "," or operator next to each other, there will be two special characters next to each other
Do While InStr(str, Chr(1) & Chr(1)) > 0
str = Replace(str, Chr(1) & Chr(1), Chr(1))
Loop
' Remove special character at the end of the string:
If Right(str, 1) = Chr(1) Then str = Left(str, Len(str) - 1)

TokeniseTheString = Split(str, Chr(1))

End Function

使用此字符串进行测试 IF(TestValue>=0,TestValue,-TestValue) 为我提供了所需的解决方案。

Sub test()
Dim TokenArray() As String
TokenArray = TokeniseTheString("IF(TestValue>=0,TestValue,-TestValue)")
End Sub

我以前从未见过正则表达式并尝试实现 this进入VBA。我遇到的问题是 VBA 中的 RegExp 对象不允许 positive lookbehind .

如果有任何比我上面的解决方案更有效的解决方案,我将不胜感激。

最佳答案

根据 @Florent B 的建议,以下函数使用 RegExp 给出相同的结果:

Function TokenRegex(str As String) As String()
Dim objRegEx As New RegExp
Dim strPattern As String

strPattern = "(""(?:""""|[^""])*""|[^\s()+\-\/*^<>=,]+|<=|>=|\S)\s*"
With objRegEx
.Global = True
.MultiLine = False
.IgnoreCase = True
.Pattern = strPattern
End With

str = objRegEx.Replace(str, "$1" & ChrW(-1))
If Right(str, 1) = ChrW(-1) Then str = Left(str, Len(str) - 1)
TokenRegex = Split(str, ChrW(-1))

End Function

关于regex - 在 VBA 中对数学(中缀)表达式进行标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56815361/

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