如何确定复合格式字符串是否无效?

时间:2010-04-16 18:59:54

标签: c# .net string.format

Per the documentation,如果(A)格式字符串无效或(B)格式字符串包含在args数组中找不到的索引,String.Format将抛出FormatException

我希望能够确定哪些条件(如果有的话)在任意字符串和参数数组中失败。

有什么能帮我的吗?谢谢!

4 个答案:

答案 0 :(得分:2)

跟进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,并检查错误消息的开头。另外,如果你需要捕获格式字符串是什么,以及args是什么,你需要做这样的事情:

        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 );

        }

编辑:添加了简单的正则表达式来计算格式标记。可能有帮助...

希望这会有所帮助。祝你好运!

答案 1 :(得分:1)

在每种情况下,FormatException消息属性都设置为不同的消息。

答案 2 :(得分:0)

你不想做......?

works = true;
try {
  String.Parse(Format, ObjectArray);
} catch FormatException {
works = false; }

答案 3 :(得分:0)

我最近使用下面的正则表达式来验证所有资源文件中的复合格式字符串

    /// <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

相关问题