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

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

我该怎么做?

最佳答案

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

Private Function nonEmptyFields(ParamArray strings() As Variant) As String
    nonEmptyFields = WorksheetFunction.TextJoin(",", True, Array(strings))
End Function

enter image description here

Note: This will only work for Office 365+, but you can always create your own version of TEXTJOIN

<小时/>

另一种选择是循环遍历字符串的 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

通过设置两者都会产生期望的结果

    Debug.Print nonEmptyFields(a, b, c, d, e, f) ' "", "b", "c", "", "", ""

enter image description here

关于regex - 连接字符串并删除多余的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55576967/

相关文章:

excel - 当前范围内缺少、重复的声明

vba - 扩展 VBA 代码以删除整个工作簿的某些单元格的字符

java - 将文件名分成组

regex - 用于查找电话号码的正则表达式

python - python 正则表达式分组的最佳实践

excel - 如何编写执行预定义查询以将数据加载到工作表中的办公脚本?

C# 分割逗号分隔值

python - 通过 Python 2.7 在 .xls 上写入多列

java - 比较Hashmap下载excel中的数据

excel - 目标以目标为公式寻求宏观