Search code examples
vbscriptasp-classic

Replace a comma in between two double quotes


I would like to replace a comma in between two double quotes.

EXAMPLE:

Replace:

11/18/2015,15:27,1,103,3,,,197179,"Petco, Inc.",Amy,Jr,187.061,452.5,0,0,0,2.419,0,0,37.38,489.88`

With:

11/18/2015,15:27,1,103,3,,,197179,"Petco Inc.",Amy,Jr,187.061,452.5,0,0,0,2.419,0,0,37.38,489.88

NOTE: I still want to keep the bare commas I just want to replace any commas that are inside of the double quote "

I know I can replace the commas by doing this: strText = Replace(strText, ",", "")

but how do I do that in between the two double quotes only and not affect the other commas that are outside of the double quotes.

Tried this thanks to pee2pee but getting an error: Expected identifier

.Pattern    = "/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g"
-------------------^


  dim re
  Set re = New RegExp
  With re
      .Pattern    = "/(""".*?"""|[^""",\s]+)(?=\s*,|\s*$)/g"
      .IgnoreCase = False
      .Global     = False
  End With
  Set re = Nothing

Thanks


Solution

  • 1 - Classic one:

    csv = "..." ' your lines
    ReDim chars(Len(csv) - 1) 'array for output
    wearein = False
    For i = 1 To Len(csv)
        chars(i-1) = Mid(csv, i, 1)
        Select Case chars(i-1)
            Case Chr(34) 'we're in
                wearein = Not wearein
            Case ","
                If wearein Then chars(i-1) = ""
        End Select
    Next
    newstr = Join(chars, "")
    Response.Write newstr
    

    2 - By using RegExp and a callback function :

    Function ReplaceCallback(match, position, all)
        ReplaceCallback = Replace(match, ",", "")
    End Function
    
    Set re = New RegExp
        re.Pattern = """[^""]*,[^""]*"""
        re.Global = True
    
    csv = "..." 'your lines
    newstr = re.Replace(csv, GetRef("ReplaceCallback")) 'replace done
    Response.Write newstr
    

    3 - By mixing MS JScript and VBScript:

    <script language="JScript" runat="server">
    function removeCommas(text){
        return text.replace(/"[^"]*,[^"]*"/g, function(){return arguments[0].replace(/,/g, "")});
    }
    </script>
    <%
    csv = "..." 'your lines
    Response.Write removeCommas(csv)
    %>