mukulsharma1146
mukulsharma1146

Reputation: 171

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

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

Upvotes: 2

Views: 684

Answers (3)

vks
vks

Reputation: 67968

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

Upvotes: 0

Reasurria
Reasurria

Reputation: 1848

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.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

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+)"

Upvotes: 1

Related Questions