Split string with comma delimiter but not if it is a currency value using C#

695 views Asked by At

I have to split a string which contains normal values as well as currency values

i.e. aaa,bbb,$33,222,ccc,$22,000

Output expected :

-aaa
-bbb
-$33,222
-ccc
-$22,000
3

There are 3 answers

1
Reasurria On BEST ANSWER

Just giving a non-regex answer for some variety. You could do the following:

String[] MySplit(String str)
{
    bool currency = false;
    char[] chars = str.ToCharArray();

    for(int i = 0; i < str.Length(); ++i)
    {
       if(chars[i] == '$')
          currency=true;
       else
       if(currency && chars[i] == ',')
       {
           chars[i] = '.';
           currency = false;
       }
    }
    return new String(chars).Split(",");
}

This replaces the currency commas with full stops or whatever you want so that you can comfortably split the string on commas. You can always change it back to commas once you have the tokens. Note that this only works under the assumptions that currency values will always have decimals.

8
Avinash Raj On

Just split according to the below regex.

@",(?!\d)"

This will match all the commas which are not followed by a digit. (?!\d) asserts that the match must not be followed by a digit.

DEMO

In c# this should work.

@"(?<!\$\d+),(?!\d+)"
0
vks On

I would suggest grab the capture instead of split.

(\$\d+(?:,\d+)*(?:\.\d+)*)|([^,\n]+)

Try this.See demo.You can later append - to each capture or group result.

https://regex101.com/r/nS2lT4/14