0

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("\"", "");
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Henry
  • 17
  • 4
  • 10
    Seeing this looks like CSV, you might want to use an actual CSV parser rather than regex. – gunr2171 Dec 29 '22 at 22:10
  • 4
    I concur. CSV is a deceptively simple format with a significant number of edge cases. Unless this is a learning exercise, you're better off using a CSV parsing library that's readily available, like [this one](https://github.com/nreco/csv). – Robert Harvey Dec 29 '22 at 22:12
  • 1
    And ***if it is*** a learning exercise, learning how to work with CSV is part of that exercise, Regardless of whether you use a library, 1) read CSV, 2) modify record property values, 3) write CSV. – madreflection Dec 29 '22 at 22:14
  • Try: `Console.WriteLine(Regex.Replace("12,\"text, is\",\"another 25,000\",23,\"hello\"", ",(?=([^\"]*\"[^\"]*\")+[^\"]*\"[^\"]*$)", ""));` – Bart Kiers Dec 29 '22 at 22:24

1 Answers1

1

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

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215