查找和替换文件中的字符串

问题描述 投票:1回答:1

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

所以,你能告诉我在一个文件中找到这些关键字的最简单的方法吗?

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

先谢谢你

c# file replace find
1个回答
2
投票

这就是我想出的办法:我使用了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
© www.soinside.com 2019 - 2024. All rights reserved.