[英]Regex to remove the third number and add commas
我有以下所有數字數據:
4245 4 553.4 0242 4424.09 2 422404 5955 452
2234234.234 224 -345.25
2423 -234 64.69
我需要單獨處理每一行。 我需要刪除每個第三個數字,並用逗號將其輸出如下:
請僅注意每組后的空格 :
4245,4, 0242,4424.09, 422404,5955
2234234.234,224
2423,-234
在一些幫助下 ,我能夠刪除第三個零,但是第三個數字現在可以是任何值:
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 ? "" : ",");
但是無法弄清楚如何刪除第三個數字(無論是否為零)。 任何幫助,將不勝感激。 謝謝。
您可以使用string.Split
, string.Join
和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));
將輸出
4245,4,0242,4424.09,422404,5955
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.