【问题标题】:Find and Replace string in a file C#在文件 C# 中查找和替换字符串
【发布时间】:2020-08-12 01:08:47
【问题描述】:

我想找到并获取关键字,然后从另一个关键字匹配,然后替换字典中的值。您可以在我的文本文件中看到下面的内容。所以,我需要找到$,然后我需要取花括号内的单词。例如,我需要取用户名、服务名称和服务描述。

那么你能告诉我在文件中找到它的最简单方法,并按照我上面描述的那样获取关键字。

Hi ${username},
Following services has reported  some issue:
${serviceName}: ${serviceDescription}

提前致谢

【问题讨论】:

  • 看看String.Format
  • 你试过了吗?另外:你想解决什么问题?我有一种感觉,这可能是 x-y。
  • 用“正则表达式”怎么样?它应该简单、快速。
  • 根据字典和文件的大小,您甚至可以只使用string.Replace(string,string)
  • @abhijat_saxena:谢谢这就是我正在寻找的......正则表达式有魔力。所以我将其标记为已解决。

标签: c# file replace find


【解决方案1】:

这就是我想出的:
我使用了 C# 正则表达式并将匹配项替换为字典中的相应值

class Program
    {
        static readonly Regex re = new Regex(@"\$\{(\w+)\}", RegexOptions.Compiled);
        static void Main(string[] args)
        {
            var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
                { "username", "alpha" },
                { "serviceName", "azure service" },
                { "serviceDescription", "azure service has stopped" }
           };

            var log = File.ReadAllText("log.txt");

            string output = re.Replace(log, match => dict[match.Groups[1].Value]);
        }
    }

你的输出看起来像这样

Hi alpha,
Following services has reported  some issue:
azure service: azure service has stopped

【讨论】:

  • 非常感谢你,这就是我要找的。​​span>
猜你喜欢
  • 2011-05-25
  • 2013-02-19
  • 1970-01-01
  • 1970-01-01
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-22
相关资源
最近更新 更多