Regex to search for single 0s and add commas

I have the following number data:

4245 4 0 0242 4424.09 0 422404 5955 0
2234234.234 224 0
2423 234 0

I need to process each row individually. I need to remove all single 0s and output as follows with commas:

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

I got the part of deleting individual digits:

var result = Regex.Replace(inData, @"\b\s0\b", string.Empty);

But I can’t figure out how to add commas between each number. Any help would be greatly appreciated. Thank.

+4
source share
4 answers

You can achieve what you want with a single operation Regex.Replace, but with the help of a specialized compliance evaluator:

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 ? "" : ",");

enter image description here

, , , , .

:

  • (?:\s+|^)0(\s+) - 0, , , 1 ( 0 1)
  • | -
  • (\s+0)$ - 2, , 0 ($)
  • | -
  • \s+ - (3- ) 1 .

, , , 0 , 1 , 0 String.Replace.

var inp = "4245 4 0 0242 4424.09 0 422404 5955 0";
inp = inp.EndsWith(" 0") ? inp.Substring(0, inp.Length - 2) : inp;
var output = Regex.Replace(inp.Replace(" 0 ", ", "), @"(\d) (\d)", "$1,$2");
+2

,

  • ( "xy z" = > "xy, z" )
  • ( "xy 0 z" = > "xy, z" )

:

  • inData.replace(" ", ",");,
  • inData.replace(",0", " ");
+1

.

var result = Regex.Replace(inData, @"\s+", ",");

\s+ .

, 0

+1
source

You can just create string.replace (",", "), right? (If I understand your question correctly)

Or you can even make string.split ("") into an array and then string.join (','). Although it is probably less effective.

0
source

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


All Articles