【问题标题】:c# String formatter with % placeholders?c# 带有 % 占位符的字符串格式化程序?
【发布时间】:2020-07-02 15:58:42
【问题描述】:

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

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

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

当我匹配一个特定的 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# 中替换这些占位符?

谢谢

P.S.:我不知道一个描述有多少个占位符。

【问题讨论】:

  • “我不知道一个描述有多少个占位符。”好吧,您提到了string.Format,如果您不知道参数,您将如何使用它?
  • 您可以传递要使用的参数数组。参数本身将匹配要格式化的“描述”,包括它在技术上具有多少元素。这里:docs.microsoft.com/en-us/dotnet/api/…

标签: c# .net event-viewer


【解决方案1】:

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

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

【讨论】:

  • 感谢您的建议,但是这不是仅适用于单个索引吗?我需要执行某种 while 循环,直到没有更多的占位符匹配正确?
  • 不,它适用于任意数量的索引,不需要 while 循环。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 1970-01-01
  • 2016-03-16
相关资源
最近更新 更多