English 中文(简体)
How can I determine if a composite format string is invalid?
原标题:

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!

最佳回答

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!

问题回答

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

And you don t want to do...?

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

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





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签