複合形式の文字列が無効であるかどうかを判断するにはどうすればよいですか?
-
27-09-2019 - |
質問
ドキュメントごと, String.Format
スローします FormatException
いずれかの場合(a)形式の文字列が無効であるか、(b)形式の文字列には、ARGSアレイにはないインデックスが含まれています。
これらの条件のどちらが任意の文字列と引数の配列で失敗するかを判断できるようにしたいと思います。
私のためにできることはありますか?ありがとう!
解決
Gbogumilの回答にフォローアップしてください。最初のケースでは、次のようになります。
"Input string was not in a correct format."
そして2番目に、あなたは得ます:
"Index (zero based) must be greater than or equal to
zero and less than the size of the argument list."
(ユーザーメッセージまたはロギングの場合)を確認する必要がある場合は、QOR72のようにトライキャッチを使用して、エラーメッセージが始まるものを確認できます。さらに、フォーマット文字列が何であり、ARGが何であるかをキャプチャする必要がある場合は、次のようなことをする必要があります。
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 );
}
編集: 形式のトークンをカウントするために、単純なRegexを追加しました。役立つかもしれません...
お役に立てれば。幸運を!
他のヒント
Formatexceptionメッセージプロパティは、これらの各ケースで明確なメッセージに設定されます。
そして、あなたはやりたくありません...?
works = true;
try {
String.Parse(Format, ObjectArray);
} catch FormatException {
works = false; }
私は最近、以下の次の正規表現を使用して、すべてのリソースファイルの複合形式の文字列を検証しました
/// <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);
Compositeフォーマットされた文字列の詳細については、参照してください http://msdn.microsoft.com/en-us/library/txafckwd(v=vs.110).aspx
所属していません StackOverflow