首页 > 解决方案 > c# 带有 % 占位符的字符串格式化程序?

问题描述

作为一个项目,我一直在构建一个日志解析器。

它的功能之一是解析和识别事件查看器文件中的特定匹配项。

我的实现一切正常,但是我遇到了一个小障碍。

当我匹配一个特定的 EventRecord 时,我会去获取 ProviderMetadata,它会有事件描述。

我的问题是事件描述使用“%1,%2,...”作为占位符,而不是 StringFormat 使用的 {1}。

下面是一个描述示例:

%1 
Device is AAD joined ( AADJ or DJ++ ): %2 
User has logged on with AAD credentials: %3 
Windows Hello for Business policy is enabled: %4 
Windows Hello for Business post-logon provisioning is enabled: %5 
Local computer meets Windows hello for business hardware requirements: %6 
User is not connected to the machine via Remote Desktop: %7 
User certificate for on premise auth policy is enabled: %8 
Machine is governed by %9 policy. 
See https://go.microsoft.com/fwlink/?linkid=832647 for more details.

因为我可能需要格式化数十个描述,所以我正在寻找一个高性能的解决方案。如何格式化此字符串并在 C# 中替换这些占位符?

谢谢

PS:我不知道一个描述提前有多少个占位符。

标签: c#.netevent-viewer

解决方案


一个简单的方法是使用Regex.Replace

var result = Regex.Replace(input, @"%(\d+)", m => 
    /* build the replacement for index Convert.ToInt32(m.Groups[1].Value) */);

推荐阅读