简体   繁体   English

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

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

I want to find and take the keyword and then match from another keyword and then replace the values from the dictionary.我想找到并获取关键字,然后从另一个关键字匹配,然后替换字典中的值。 You can see the content below which is in my text file.您可以在我的文本文件中看到下面的内容。 So, I need to find the $, and then I need to take the words which are within curly braces.所以,我需要找到$,然后我需要取花括号内的单词。 For example, I need to take username,serviceName and serviceDescription.例如,我需要获取用户名、服务名称和服务描述。

So can you please tell me the easiest way to find this in a file and take the keywords as I described above.所以你能告诉我在文件中找到它并使用我上面描述的关键字的最简单方法。

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

Thanks in Advance提前致谢

This is what I came up with:这就是我想出的:
I used C# Regular expressions and replaced the matches with the corresponding values in the dictionary我使用了 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]);
        }
    }

Your output would look something like this你的 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