-2
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

9
  • Please add code and data as text (using code formatting), not images. Images: A) don't allow us to copy-&-paste the code/errors/data for testing; B) don't permit searching based on the code/error/data contents; and many more reasons. Images should only be used, in addition to text in code format, if having the image adds something significant that is not conveyed by just the text code/error/data.
    – gunr2171
    Commented Jun 8, 2022 at 1:37
  • Does this need to be regex? Is your input always "Letter Number Plus Letter Number"?
    – gunr2171
    Commented Jun 8, 2022 at 1:38
  • Why are you always printing "0", and always matching specifically "A1"?
    – gunr2171
    Commented Jun 8, 2022 at 1:48
  • @gunr2171 This is just an example.
    – Dev006
    Commented Jun 8, 2022 at 1:51
  • You didn't answer my first two questions, so I'm going to assume that your input format is as I described, your expected output for your example is {A1}+{A1}, and regex is not needed.
    – gunr2171
    Commented Jun 8, 2022 at 1:56

2 Answers 2

1

You can use

pattern = $@"\b(?!{columnCode}\d){columnCode}\b";

See the resulting regex demo. It matches

  • \b - a word boundary
  • (?!A1\d) - fail the match if there is A1 + a digit
  • A1 - a fixed text
  • \b - a word boundary.
-1

This pattern worked for my Scenario.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.