Home > other >  How do I remove commas inside double quotes?
How do I remove commas inside double quotes?

Time:12-30

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("\"", "");

CodePudding user response:

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

CodePudding user response:

I subscribe Rober Harvey's comment, being able choose the right tool for the job is a skill. In any case, simply for academic purposes, directly answering your question, the use of regex for a string like the sample you show could look like this:

string RemoveCommas(string original)
{
    var regex = new Regex("\".*?\"");
    return regex.Replace(original, s => s.Value.Replace(",", ""));;
}

Sample program: https://dotnetfiddle.net/TThL8U

  •  Tags:  
  • c#
  • Related