C# 使用正则表达式分割 string.format 字符串

red*_*der 1 c# regex string.format split

我希望能够在变量的位置指示器上拆分格式化字符串。它将删除花括号和它们之间指示数字的位置。
所以,字符串:

string format = "{0} field needs to be set to '{1}' when {2},  Fixit.  NOW!";
Run Code Online (Sandbox Code Playgroud)

应解析为 3 个字符串。

  • “该字段需要设置为‘”
  • “' 什么时候 ”
  • “,修复。现在!”

我们使用像上面的“格式”这样的字符串来构建错误消息。我的目标是添加通用单元测试,可以采用该格式并验证是否生成了与预期格式匹配的错误消息。由于错误生成代码和单元测试引用相同的格式,因此当对消息进行微小更改时,不需要更新单元测试。

在上面的示例中,我将能够通过调用名为 SplitFormatString 的新方法来测试预期结果。

string fieldName = "UserName";
string expectedValue = "Bob";
string condition = "excellence is a must";
string errorMessage = TestFieldValueErrorCase( );
AssertStringContainsAllThese(errorMessage, SplitFormatString(format), fieldName, expectedValue,condition);
Run Code Online (Sandbox Code Playgroud)

经过验证

public static void AssertStringContainsAllThese(string msg, string[] formatChunks, params string[] thingsToFind)
{
  foreach (var txt in formatChunks.Concat(thingsToFind))
  {
    Assert.IsTrue(msg.Contains(txt), "Could not find <<" + txt + ">> in msg >>> " + msg);               
  }
}
Run Code Online (Sandbox Code Playgroud)

我宁愿使用正则表达式,也不愿使用不优雅的子字符串方法。

mr_*_*reb 5

我想你会想要Regex.Split

在正则表达式模式定义的位置将输入字符串拆分为子字符串数组。

Regex.Split("{0} field needs to be set to '{1}' when {2},  Fixit.  NOW!", @"{\d+}");
Run Code Online (Sandbox Code Playgroud)

应该输出:

["","field needs to be set to '","' when ",",  Fixit.  NOW!"]
Run Code Online (Sandbox Code Playgroud)