gpt4 book ai didi

c# - String.Format 计算预期参数的数量

转载 作者:可可西里 更新时间:2023-11-01 08:41:39 26 4
gpt4 key购买 nike

是否可以计算 String.Format() 字符串中预期参数/参数的数量?

例如:“你好{0}。再见{1}” 应该返回计数 2。

我需要在 string.Format() 抛出异常之前显示错误。

感谢您的帮助。

最佳答案

您可以使用正则表达式,例如 {(.*?)} 然后只计算匹配项。如果您需要处理 {0} {0} 之类的情况(我想应该返回 1),那么这会变得有点困难,但是您总是可以将所有匹配项放在一个列表中,然后在其上执行 Linq select distinct .我在想类似下面的代码:

var input = "{0} and {1} and {0} and {2:MM-dd-yyyy}";
var pattern = @"{(.*?)}";
var matches = Regex.Matches(input, pattern);
var totalMatchCount = matches.Count;
var uniqueMatchCount = matches.OfType<Match>().Select(m => m.Value).Distinct().Count();
Console.WriteLine("Total matches: {0}", totalMatchCount);
Console.WriteLine("Unique matches: {0}", uniqueMatchCount);

编辑:

我想解决评论中提出的一些问题。下面发布的更新代码处理存在转义括号序列(即 {{5}})、未指定参数的情况,并且还返回最高参数的值 + 1。代码假定输入字符串将格式良好,但在某些情况下这种权衡可能是可以接受的。例如,如果您知道输入字符串是在应用程序中定义的,而不是由用户输入生成的,则可能没有必要处理所有边缘情况。也可以使用单元测试来测试要生成的所有错误消息。我喜欢这个解决方案的一点是,它很可能会处理抛给它的绝大多数字符串,而且它比确定的解决方案更简单 here (建议重新实现 string.AppendFormat)。我会解释这样一个事实,即这段代码可能无法通过使用 try-catch 并仅返回“无效的错误消息模板”或类似的东西来处理所有边缘情况。

下面代码的一个可能改进是更新正则表达式以不返回前导“{”字符。这将消除对 Replace("{", string.Empty) 的需要。同样,此代码可能并非在所有情况下都是理想的,但我认为它足以解决所提出的问题。

const string input = "{0} and {1} and {0} and {4} {{5}} and {{{6:MM-dd-yyyy}}} and {{{{7:#,##0}}}} and {{{{{8}}}}}";
//const string input = "no parameters";
const string pattern = @"(?<!\{)(?>\{\{)*\{\d(.*?)";
var matches = Regex.Matches(input, pattern);
var totalMatchCount = matches.Count;
var uniqueMatchCount = matches.OfType<Match>().Select(m => m.Value).Distinct().Count();
var parameterMatchCount = (uniqueMatchCount == 0) ? 0 : matches.OfType<Match>().Select(m => m.Value).Distinct().Select(m => int.Parse(m.Replace("{", string.Empty))).Max() + 1;
Console.WriteLine("Total matches: {0}", totalMatchCount);
Console.WriteLine("Unique matches: {0}", uniqueMatchCount);
Console.WriteLine("Parameter matches: {0}", parameterMatchCount);

关于c# - String.Format 计算预期参数的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4989106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com