连接字符串并删除多余的逗号

时间:2019-04-08 15:33:09

标签: regex excel vba

我正在尝试连接多个字符串并以逗号分隔它们, 然后删除多余的,前导和尾随的逗号。

例如,输入TEST("", "b", "c", "", ""),我想得到 b, c

但是,我的正则表达式,$| ,+|^,并没有真正考虑重复的逗号:

Function TEST(a, b, c, d, e)
    res = a & ", " & b & ", " & c & ", " & d & ", " & e

    Debug.Print (res)
    Dim regex As Object, str, result As String
    Set regex = CreateObject("VBScript.RegExp")

    With regex
      .Pattern = ",$| ,+|^,"
    End With

    Dim ReplacePattern As String
    ReplacePattern = ""

    res = regex.Replace(res, ReplacePattern)

    TEST = res
End Function

我该怎么做?

2 个答案:

答案 0 :(得分:4)

@ScottCraner对TEXTJOIN 的建议最为优雅(如果他希望将其发布为自己的,则将删除部分答案)

https://example.com/folder1/index.php

enter image description here

  

注意:这仅适用于Office 365+,但您始终可以create your own version of TEXTJOIN


另一种选择是遍历字符串Private Function nonEmptyFields(ParamArray strings() As Variant) As String nonEmptyFields = WorksheetFunction.TextJoin(",", True, Array(strings)) End Function 并将其添加到一起,具体取决于它们的内容(是填充还是空)

ParamArray

通过设置

都将产生预期的结果
Private Function nonEmptyFields(ParamArray strings() As Variant) As String

    Dim result As String
    Dim i As Byte

    For i = LBound(strings) To UBound(strings)
        If Len(strings(i)) <> 0 Then
            If result = vbNullString Then
                result = strings(i)
            Else
                result = result & "," & strings(i)
            End If
        End If
    Next i

    nonEmptyFields = result

End Function

enter image description here

答案 1 :(得分:1)

我的丑陋解决方案保持相同的参数:

Function TEST(a, b, c, d, e)

    If a <> "" Then res = a

    If b <> "" Then
        If res <> "" Then
            res = res & ", " & b
        Else
            res = b
        End If
    End If

    If c <> "" Then
        If res <> "" Then
            res = res & ", " & c
        Else
            res = c
        End If
    End If

    If d <> "" Then
        If res <> "" Then
            res = res & ", " & d
        Else
            res = d
        End If
    End If

    If e <> "" Then
        If res <> "" Then
            res = res & ", " & e
        Else
            res = e
        End If
    End If

    TEST = res

End Function

img1