0

I have the following all 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 line individually. I need to remove each third number and output as follows with commas:

Note 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 cannot figure out how to remove the third number whether its zero or not. Any help would be appreciated. Thanks.

Community
  • 1
  • 1
Robert Smith
  • 779
  • 1
  • 10
  • 28

1 Answers1

3

You could do this with string.Split, string.Join, and 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

juharr
  • 31,741
  • 4
  • 58
  • 93
  • Thank you Juharr! One quick question, is there a way to maintain the commas in the following format: (space only after each set as seen in the output above) 4245,4, 0242,4424.09, 422404,5955 – Robert Smith Sep 13 '16 at 15:07
  • @RobertSmith Yeah, I've updated my answer to attempt to handle that as well. It's a bit more messy as I'm just adding a space to the beginning of the next string after the one that was removed. – juharr Sep 13 '16 at 15:16
  • Juharr thank you, good job. Would it be possible using an all regex solution? (without using split/linq) I would like to compare it to the current all-regex above. Thank you. – Robert Smith Sep 13 '16 at 15:56
  • @RobertSmith The closest I can think of would be `Regex.Replace(input, @"(\S+)\s(\S+)\s\S+", "$1,$2,").TrimEnd(',');`. – juharr Sep 13 '16 at 16:13
  • Juharr thanks! Great solution and great job, I marked your post as the answer. – Robert Smith Sep 13 '16 at 17:54