Come è possibile determinare se una stringa di formato composita non è valido?
-
27-09-2019 - |
Domanda
Per la documentazione , String.Format
lancerà una FormatException
se uno ( a) la stringa di formato è valido o (B) la stringa di formato contiene un indice che non può essere trovato nell'array args.
Voglio essere in grado di determinare quale (se uno) di queste condizioni non riescono a qualsiasi stringa arbitraria e matrice di argomenti.
C'è qualcosa che può fare per me? Grazie!
Soluzione
Follow-up alla risposta di gbogumil, nel primo caso si ottiene:
"Input string was not in a correct format."
e nel secondo, si ottiene:
"Index (zero based) must be greater than or equal to
zero and less than the size of the argument list."
Se avete bisogno di senso che (per la messaggistica utente o la registrazione), allora si potrebbe utilizzare un tentativo di cattura come qor72 suggerito, e controllare ciò che il messaggio di errore inizia con. Inoltre, se hai bisogno di catturare ciò che la stringa di formato è stato, e ciò che gli args erano, si avrà bisogno di fare qualcosa di simile:
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 );
}
Modifica Aggiunta la semplice espressione regolare per contare i token di formato. Potrebbe aiutare ...
Spero che questo aiuti. Buona fortuna!
Altri suggerimenti
La proprietà messaggio FormatException è impostata su un messaggio distinta in ognuno di questi casi.
E non si vuole fare ...?
works = true;
try {
String.Parse(Format, ObjectArray);
} catch FormatException {
works = false; }
Recentemente ho usato la seguente espressione regolare di seguito per convalidare le stringhe di formato composite in tutti i nostri file di risorse
/// <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);
Per ulteriori informazioni sulle stringhe formattate compositi, vedere http://msdn.microsoft.com/en-us/library/txafckwd(v=vs.110).aspx