繁体   English   中英

在文件 C# 中查找和替换字符串

[英]Find and Replace string in a file C#

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

所以你能告诉我在文件中找到它并使用我上面描述的关键字的最简单方法。

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

提前致谢

这就是我想出的:
我使用了 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]);
        }
    }

你的 output 看起来像这样

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM