Regex remove the third number and add commas

I have the following number data:

4245 4 553.4 0242 4424.09 2 422404 5955 452
2234234.234 224 -345.25
2423 -234 64.69

I need to process each row individually. I need to remove every third number and print it as follows with commas:

Pay attention to the space only after each set:

4245,4, 0242,4424.09, 422404,5955
2234234.234,224
2423,-234

With some help , I was able to remove the third zero, but the third number can be any value now:

var input = "4245 4 0 242 4424.09 0 422404 5955 0";
var results = Regex.Replace(input, @"(?:\s+|^)0(\s+)|(\s+0)$|\s+", m =>
m.Groups[1].Success ? ", " :
m.Groups[2].Success ? "" : ",");

But I can’t understand how to remove the third number, whether it is zero or not. Any help would be greatly appreciated. Thank.

0
source share
1 answer

You can do this with string.Split, string.Joinand Linq.

var input = "4245 4 553.4 0242 4424.09 2 422404 5955 452";
var results = string.Join(
        ",",
        input.Split()
            .Select((s, i) => new { Value = s, Index = i + 1 })
            .Where(x => x.Index % 3 != 0)
            .Select(x => (x.Index % 3 == 1 && x.Index != 1 ? " " : string.Empty) + x.Value));

Will output

4245.4, 0242.4424.09, 422404.5955

+3

Source: https://habr.com/ru/post/1653321/


All Articles