How to validate format for string.Format method

后端 未结 4 814
感情败类
感情败类 2021-02-14 05:15

string.Format has following method signature

string.Format(format, params, .., .. , ..);

I want to pass custom format each time like



        
相关标签:
4条回答
  • 2021-02-14 05:43

    Let's think about this API, if it exists. The goal is to pre-validate a format string, to make sure String.Format won't throw.

    Note that any string which doesn't contain a valid format slot is a valid format string - if you don't try to insert any replacements.

    -> So we would need to pass in the number or args we expect to replace

    Note that there are tons of different specialty formatting patterns, each with a specific meaning for specific types: http://msdn.microsoft.com/en-us/library/system.string.format.aspx

    Although it seems that String.Format won't throw if you pass a format string which doesn't match your argument type, the formatter becomes meaningless in such cases. e.g. String.Format("{0:0000}", "foo")

    -> So such an API would be truly useful only if you passed the types of the args, as well.

    If we already need to pass in our format string and an array of types (at least), then we are basically at the signature of String.Format, so why not just use that and handle the exception? It would be nice if something like String.TryFormat existed, but to my knowledge it doesn't.

    Also, pre-validating via some API, then re-validating in String.Format itself is not ideal perf-wise.

    I think the cleanest solution might be to define a wrapper:

    public static bool TryFormat(string format, out string result, params Object[] args)
    {
       try
       {
          result = String.Format(format, args);
          return true;
       }
       catch(FormatException)
       {
          return false;
       }
    }
    
    0 讨论(0)
  • 2021-02-14 05:50

    As long as you're only passing in 1 argument, you can look search custFormat for {0}. If you don't find it, it's invalid.

    0 讨论(0)
  • 2021-02-14 05:58

    You can validate with try catch, if format throw exceptin you log information and stop treatment.

    try 
    { 
       string.Format(custFormat, params, .., .. , ..);
    }
    catch(FormatException ex)  
    { 
      throw ex;
    }
    
    string message = ProcessMessage(custFormat, name);
    
    0 讨论(0)
  • 2021-02-14 05:59

    You should use regular expressions for syntax checking and you may use some semantic checking as well.

    Regular expression should be: (*{\d+}*)+

    0 讨论(0)
提交回复
热议问题