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

标签 regex excel vba tokenize mathematical-expressions

我需要使用 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/

相关文章:

regex - MariaDB:带有 [.character.] 的 REGEX 不再起作用(“不支持 POSIX 整理元素”)

R 中的正则表达式 strsplit 表达式,因此它仅适用于每个字符串中特定字符的第一次出现?

VBA 转到下一个过滤的单元格

Jquery 正则表达式验证

java - Java 中的替换模式

excel - 以特定格式转置

excel - 在 .txt 文件中特定行的特定位置插入空格

excel - 在获取 Excel 工作簿中所有工作表名称的列表期间,VBA 代码的执行速度非常慢

vba - 使用 VBA 和 VB.NET API 处理多个窗口

excel - 需要使用VBA将xls工作簿保存为xlsb