Henry
Henry

Reputation: 17

How do I remove commas inside double quotes?

For example, my row could contain:

12,"text, is","another 25,000",23,"hello"

I want my result to be:

12,"text is","another 25000",23,"hello"

I've tried and failed ways to do this. For example:

public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    //String Pattern = "(?<=\".*),(?=.*\")";
    //String Result = Regex.Replace(Row.Column0.Trim(), Pattern, "@");
    //String Result = Regex.Replace(Row.Column0, @"[\""]", "", RegexOptions.None);
    //String Result = Row.Column0.Replace("0,", "0|").Replace("1,", "1|").Replace("2,", "2|").Replace("3,", "3|").Replace("4,", "4|").Replace("5,", "5|").Replace("6,", "6|").Replace("7,", "7|").Replace("8,", "8|").Replace("9,", "9|");
    //String Result = Row.Column0.Replace("\",", "|").Replace(",\"", "|");
    //String Result = Row.Column0.Replace(",", "").Replace("\"", "");

Upvotes: 0

Views: 186

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

Technically, you can implement a simple FSM (Finite State Machine) with just two states inQuotation (which can be true or false):

private static string RemoveCommas(string value, 
                                   char comma = ',', 
                                   char quotation = '"') {
  if (string.IsNullOrEmpty(value))
    return value;

  var result = new StringBuilder(value.Length);

  bool inQuotation = false;

  foreach (char c in value)
    if (c != ',' || !inQuotation) {
      result.Append(c);

      if (c == '"')
        inQuotation = !inQuotation;
    } 

  return result.ToString();
}

Fiddle

But aren't you looking for a CSV parsing?

Parsing CSV files in C#, with header

Upvotes: 1

Related Questions