我怎样才能确定一个复合格式字符串是无效的?
-
27-09-2019 - |
题
每所述文档,String.Format
将抛出FormatException
如果( A)格式字符串无效或(B)的格式字符串包含无法args数组中找到的索引。
我希望能够确定哪些(如果任一)的那些条件失败上的参数中的任何任意字符串和数组。
有什么可以为我做?谢谢!
解决方案
跟进到gbogumil的答案,你得到的第一种情况:
"Input string was not in a correct format."
和第二,您可以:
"Index (zero based) must be greater than or equal to
zero and less than the size of the argument list."
如果您需要感,这(对用户的消息或日志记录),那么你可以像qor72建议使用try catch和检查什么用错误信息开始。另外,如果你需要采集什么格式字符串是,什么基本名字,你需要做这样的事情:
string myStr = "{0}{1}{2}";
string[] strArgs = new string[]{"this", "that"};
string result = null;
try { result = string.Format(myStr, strArgs); }
catch (FormatException fex)
{
if (fex.Message.StartsWith("Input"))
Console.WriteLine
("Trouble with format string: \"" + myStr + "\"");
else
Console.WriteLine
("Trouble with format args: " + string.Join(";", strArgs));
string regex = @"\{\d+\}";
Regex reg = new Regex(regex, RegexOptions.Multiline);
MatchCollection matches = reg.Matches(myStr);
Console.WriteLine
("Your format has {0} tokens and {1} arguments",
matches.Count, strArgs.Length );
}
修改强>增加了简单的正则表达式来计算格式令牌。可以帮助...
希望这有助于。祝你好运!
其他提示
在出现FormatException消息属性在每个这些情况下设置于不同的消息。
和你不想做的...?
works = true;
try {
String.Parse(Format, ObjectArray);
} catch FormatException {
works = false; }
我最近使用以下以下正则表达式来验证在我们所有的资源文件中的复合格式字符串
/// <summary>
/// The regular expression to get argument indexes from a composed format string
/// </summary>
/// <remarks>
/// example index alignment formatString
/// {0} 0
/// {1:d} 1 d
/// {2,12} 2 12
/// {3,12:#} 3 12 #
/// {{5}}
/// {{{6}}} 6
/// </remarks>
private static readonly Regex ComposedFormatArgsRegex =
new Regex(@"(?<!(?<!\{)\{)\{(?<index>\d+)(,(?<alignment>\d+))?(:(?<formatString>[^\}]+))?\}(?!\}(?!\}))",
RegexOptions.Compiled | RegexOptions.ExplicitCapture);
有关复合格式的字符串的更多信息,请参见 http://msdn.microsoft.com/en-us/library/txafckwd(v=vs.110).aspx
不隶属于 StackOverflow