c# - 在文件 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]);
}
}
你的输出看起来像这样
Hi alpha,
Following services has reported some issue:
azure service: azure service has stopped
推荐阅读
- object-detection - 对象检测 - 图像裁剪
- javascript - 将日期数组排序到最近的日期
- node.js - 文件上传失败;503 错误(加上 COR 错误)
- javascript - 处理多个表单提交
- excel - 使用 Regex 查找和删除字符串 - 但保留最后一个字符
- python - 在python3中创建一个全局字典变量
- apache-spark - 关于在 Spark 中加入数据框的问题
- regex - .htaccess RewriteRule 没有按照我的 yii2 高级框架的需要工作
- docker - 使用备份 dump.rdb 启动 redis 容器
- c# - 在 Unity C# 中使用 2D 数组解析 JSON