Reputation: 171
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
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
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
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.
In c# this should work.
@"(?<!\$\d+),(?!\d+)"
Upvotes: 1