以CSV格式删除不必要的数据/空格

时间:2017-06-27 13:02:21

标签: vb6

我需要有关如何在不影响其他数据空间的情况下删除数据中的空格/空格的帮助。这是我的样本数据。

12345,"        ","abcde fgh",2017-06-06,09:00,AM,"       ", US

预期产出:

12345,,"abcde fgh",2017-06-06,09:00,AM,, US

因为" "应该被视为null。

我尝试了Trim()函数,但它没有用。我也试过Regex模式,但仍然没用。

这是我的样本功能。

Private Sub Transform(delimiter As String)

   Dim sFullPath    As String
   Dim strBuff      As String
   Dim re           As RegExp
   Dim matches      As Object
   Dim m            As Variant

   If delimiter <> "," Then
      strBuff = Replace(strBuff, delimiter, ",")
   Else
        With re
            .Pattern = "(?!\B""[^""]*)" & delimiter & "(?![^""]*""\B)"
            .IgnoreCase = False
            .Global = True
        End With

        Set matches = re.Execute(strBuff)
        For Each m In matches
            strBuff = re.Replace(strBuff, ",")
        Next

        Set re = Nothing
        Set matches = Nothing  
    End If
End Sub

3 个答案:

答案 0 :(得分:0)

我会添加一个输出字符串变量,并有一个条件语句,说明输入是否为空,将其添加到输出字符串。例如(VB控制台应用程序格式,提示用户输入许多输入):

Dim input As String
Dim output As String

Do
    input = console.ReadLine()
    If Not input = " " Then
        output += input
    End If
Loop Until (end condition)

Console.WriteLine(output)

您可以将任何不需要的输入放入条件中,以将其从输出中删除。

答案 1 :(得分:0)

我认为你走在正确的轨道上。尝试将此用于正则表达式。连续两个双引号是单个双引号如何包含在字符串文字中。有些人更喜欢使用Chr(34)在字符串中包含双引号。

\B(\s)(?!(?:[^""]*""[^""]*"")*[^""]*$)

在示例字符串

上使用该表达式

12345," ","abcde fgh",2017-06-06,09:00,AM," ", US

产量

12345,"","abcde fgh",2017-06-06,09:00,AM,"", US

示例功能

Private Function Transform(ByVal strLine As String) As String
    Dim objRegEx As RegExp

    On Error GoTo ErrTransForm

    Set objRegEx = New RegExp
    With objRegEx
        .Pattern = "\B(\s)(?!(?:[^""]*""[^""]*"")*[^""]*$)"
        .IgnoreCase = False
        .Global = True
        Transform = .Replace(strLine, "")
    End With

ExitTransForm:
    If Not objRegEx Is Nothing Then
        Set objRegEx = Nothing
    End If
    Exit Function

ErrTransForm:
    'error handling code here
    GoTo ExitTransForm

End Function

信用到期的信用。我用这个答案Regex Replace Whitespaces between single quotes作为表达式的基础。

答案 2 :(得分:-3)

您的CSV文件格式不正确。 双引号不应该存在,然后用记事本打开你的CSV并用空字符串替换它们。

在此之后,您现在拥有一个真正的CSV文件,可以导入whitout问题。