【问题标题】:Regex Replace c#正则表达式替换 c#
【发布时间】:2022-06-12 15:06:46
【问题描述】:
string formattedFormula = Regex.Replace("A1+A1", "(?!A1\\d+)[A1]" , "{" + 0 + "}");

我需要 {0}+{0} 的结果。但此代码替换为 {0}{0}+{0}{0}

这只是一个例子。

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);
    }
}

我的真实密码是

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;
                }
            }

【问题讨论】:

  • 请将代码和数据添加为文本 (using code formatting),而不是图像。图片:A)不允许我们复制粘贴代码/错误/数据进行测试; B) 不允许根据代码/错误/数据内容进行搜索;和many more reasons。除了代码格式的文本之外,只有在图像添加了一些重要的东西,而不仅仅是文本代码/错误/数据传达的内容时,才应该使用图像。
  • 需要是正则表达式吗?你的输入总是“字母数字加字母数字”吗?
  • 为什么总是打印“0”,而且总是专门匹配“A1”?
  • @gunr2171 这只是一个例子。
  • 你没有回答我的前两个问题,所以我假设你的输入格式和我描述的一样,你的示例的预期输出是{A1}+{A1},不需要正则表达式.

标签: c# regex replace code-duplication


【解决方案1】:

你可以使用

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

请参阅resulting regex demo。它匹配

  • \b - 单词边界
  • (?!A1\d) - 如果有 A1 + 一个数字,则匹配失败
  • A1 - 固定文本
  • \b - 单词边界。

【讨论】:

    【解决方案2】:

    这种模式适用于我的场景。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      相关资源
      最近更新 更多