1

Given the input string "Test,,test,,,test,test"

and using the following C# snippet I would have expected the duplicate commas to be replaced by a single comma and results in...

"Test,test,test,test"

private static string TruncateCommas(string input)
{
    return Regex.Replace(input, @",+", ",");
}

Code was pinched from this answer... C# replace all occurrences of a character with just a character

But what I am seeing is "Test,,test,,,test,test" as the output from this function.

Do I need to escape the comma in the regex? Or should this regex be working.

Nattrass
  • 1,283
  • 16
  • 27

1 Answers1

2

Do I need to escape the comma in the regex?

No.

Or should this regex be working.

Yes.

Please construct your test the following way:

void Main()
{
    string s = "Test,,test,,,test,test";

    string result = TruncateCommas(s);

    Console.WriteLine(result);
}

Output

Test,test,test,test

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
  • 1
    Thankyou for making me think about this correctly. It was indeed the input. string.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}", ...). There was a space in between the commas on my input! – Nattrass Sep 09 '17 at 09:17
  • @Nattrass your welcome, glad to hear that you solved your problem. Good fortune – Mong Zhu Sep 11 '17 at 06:14