Search code examples
c#regexreplacecode-duplication

Regex Replace c#


string formattedFormula = Regex.Replace("A1+A1", "(?!A1\\d+)[A1]" , "{" + 0 + "}");

I need the result as {0}+{0}. But this code replaced like this {0}{0}+{0}{0}

this is just an example.

using System;
using System.Text.RegularExpressions;

public class HelloWorld
{
    public static void Main(string[] args)
    {
       string formattedFormula = Regex.Replace("A1+A1", "(?!A1\\d+)[A1]" , "{" + 0 + "}");
        Console.WriteLine (formattedFormula);
    }
}

My Real code is

foreach (string columnCode in parameters)
            {
                string pattern = string.Empty;

                if (!Common.Common.IsNumaric(columnCode))
                {
                    pattern = "(?!" + columnCode + "\\d+)[" + columnCode + "]";

                    stringList.Add(columnCode);
                    incrementor++;

                    formattedFormula = Regex.Replace(formattedFormula, pattern, "{" + incrementor.ToString() + "}");
                }
                else
                {
                    continue;
                }
            }

enter image description here


Solution

  • This pattern worked for my Scenario.

    pattern = "(?:\\d+["+ columnCode + "]|["+ columnCode + "]+\\d)["+ columnCode + "\\d]*";