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

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

Last post 07-23-2008, 6:11 AM by ddrudik. 1 replies.
Sort Posts: Previous Next
  •  07-23-2008, 2:25 AM 44477

    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

  •  07-23-2008, 6:11 AM 44481 in reply to 44477

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

    Raw Match Pattern:
    (?<![^,]),|(?<=,)$

    Raw Replace Pattern:
    0$0

    If you are on a platform that doesn't support (?<!) or (?<=) then the above pattern will not work for you.  In that case you may need to use a matching pattern as below:

    Raw Match Pattern:
    ^(?=,)|,(?=,|$)

    Raw Replace Pattern:
    ${0}0

    Note that the ${0} is the syntax in PHP required for the replacement referencing $0 group while following with another number, modify for your platform as required.


View as RSS news feed in XML