If I understand your question correctly, you get some format string and want to check if it is valid for your parameter array?
You may go and have a look at
Escaping in C#: characters, strings, string formats, keywords, identifiers[
^], go to the
Bonus paragraph in the
string.format escaping section.
A solution may be (tweak with the number of args and with the formatting to see it work...):
static void Main(string[] args)
{
string dynString = "This is a dynamic string {0} & {1}";
var constArgs = new object[] { "First", "Second" };
string formatted = DynFormat(dynString, constArgs);
Console.WriteLine(formatted ?? "<wrong format>");
}
private static IEnumerable<int> GetIds(string format)
{
string pattern = @"\{(\d+)[^\}]*\}";
return Regex.Matches(format ?? string.Empty, pattern, RegexOptions.Compiled)
.Cast<Match>()
.Select(m => int.Parse(m.Groups[1].Value));
}
private static bool HasSufficientArgs(string dynFormat, object[] args)
{
var ids = GetIds(dynFormat).ToArray();
return (ids.Length == 0)
|| (args != null) && (args.Length > ids.Max());
}
public static string DynFormat(string dynFormat, params object[] args)
{
return HasSufficientArgs(dynFormat, args)
? string.Format(dynFormat, args)
: null;
}
Cheers
Andi