首页 > 解决方案 > 如何使用基于正则表达式条件的分隔符在 VBA 中拆分数组?

问题描述

我有这样的输入:

apple, orange, (pear, banana, grape), mango 

我想拆分为:

apple
orange
(pear, banana, grape)
mango

我不完全理解正则表达式,但我想我会使用我在这里找到的 ,(?![^()]*)) - Java split string on comma(,) 除非在括号 () 之间

我正在使用 VBA,所以如果我将输入存储在一个数组中,我通常会这样做:

array = Split(string, ",")

但这会产生如下结果:

apple
orange
(pear
banana
grape)
mango

我不想要。

我很确定我可以找到一种方法来替换 ( 和 ),使它们从输出中消失,但我不知道如何将我的正则表达式字符串逻辑提供给我的 VBA 公式。

我认为这样的事情会起作用:

array = Split(string, ",(?![^()]*\))")

但事实并非如此。我确实启用了“Microsoft VBScript Regular Expressions 5.5”参考,但它似乎没有帮助。

任何建议表示赞赏。

谢谢,

标签: regexexcelvba

解决方案


正则表达式的替代方案:

Sub mytry()
    Dim str As String
    str = "apple, orange, (pear, banana, grape), mango "

    Dim perenSplt() As String
    perenSplt = Split(Replace(str, ")", ")("), "(")

    str = ""

    Dim i As Long
    For i = LBound(perenSplt) To UBound(perenSplt)
        If InStr(perenSplt(i), ")") Then
            perenSplt(i) = "(" & Replace(perenSplt(i), ",", "|")
        End If
        str = str & perenSplt(i)
    Next i

    Dim finalSplt() As String
    finalSplt = Split(str, ",")

    For i = LBound(finalSplt) To UBound(finalSplt)
        If InStr(str, "(") > 0 Then
            finalSplt(i) = Trim(Replace(finalSplt(i), "|", ","))
        Else
            finalSplt(i) = Trim(finalSplt(i))
        End If
    Next i

    ActiveSheet.Range("A1").Resize(,UBound(finalSplt) + 1) = finalSplt

End Sub

在此处输入图像描述


推荐阅读