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

发布于 2024-08-29 04:29:10 字数 272 浏览 3 评论 0原文

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

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

有什么可以为我做到这一点吗?谢谢!

Per the documentation, String.Format will throw a FormatException if either (A) the format string is invalid or (B) the format string contains an index that cannot be found in the args array.

I want to be able to determine which (if either) of those conditions fail on any arbitrary string and array of arguments.

Is there anything that can do that for me? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

北斗星光 2024-09-05 04:29:10

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

        }

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

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

Follow up to gbogumil's answer, in the first case you get:

"Input string was not in a correct format."

and in the second, you get:

"Index (zero based) must be greater than or equal to 
zero and less than the size of the argument list."

If you need to sense which (for user messaging or logging), then you could use a try catch like qor72 suggested, and check for what the error message starts with. In addition, if you need to capture what the format string was, and what the args were, you will need to do something like this:

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

        }

EDIT: Added the simple regex to count format tokens. Might help...

Hope this helps. Good luck!

枕梦 2024-09-05 04:29:10

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

The FormatException message property is set to a distinct message in each of those cases.

深白境迁sunset 2024-09-05 04:29:10

而你不想做...?

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

And you don't want to do...?

works = true;
try {
  String.Parse(Format, ObjectArray);
} catch FormatException {
works = false; }
踏雪无痕 2024-09-05 04:29:10

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

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

I recently used the following regular expression below to validate the composite format strings in all our resources files

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

For more information about composite formatted strings, see http://msdn.microsoft.com/en-us/library/txafckwd(v=vs.110).aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文