Got more questions? Find advice on: ASP | SQL | XML | Windows
Welcome to RegexAdvice Sign in | Join | Help

Replacing Missing Values in comma delimited file - Can this be done in one Regexp?

  •  07-23-2008, 2:25 AM

    Replacing Missing Values in comma delimited file - Can this be done in one Regexp?

    I'm processing a comma delimited string and need to *ALL* replace missing values with '0's. Leading and/or trailing ','s denote missing values. For example:

     The string ",,2,3,,,4," becomes "0,0,2,3,0,0,4,0" 

    Note that there are missing values at BOTH the beginning AND the end of the input string.

    Surprisingly I did not find any online examples of this - if someone has a solution to this it would make a good addition to a regexp library.

    My knowledge of regexps is limited  so I'm wondering if the replacement operation can be done in a single regexp pass. (I was able to do in 2 passes with the following code, however I'm wondering if there is  better approach).

                 strIn= ",,2,3,,,4,"
                 pattern:RegExp = /,(?=[,])|,$/g;            //handles all but the first missing  '0 ' - gets:  ",0,0,2,3,0,0,4,0"
                 strOut: =(strIn.replace(pattern,",0"));
                //Reset Regexp Pattern Call regexp again to handle leading ',' at BOL
                pattern = /^,/g;            
                strOut=(strOut.replace(pattern,"0,"));    // Note the replace pattern is different                                

    TIA,

    Patrick

View Complete Thread