失われた情報についてのコメントが有効ですが、いつかあなたはただ知られている書式の文字列の文字列値を取得したいだけです。
1つの方法は、私の友人によって書かれたthis blog postです。彼はstring[] ParseExact()
という拡張メソッドを実装しました。これはDateTime.ParseExact()
に似ています。データは文字列の配列として返されますが、それを使って生きることができれば、大変便利です。
public static class StringExtensions
{
public static string[] ParseExact(
this string data,
string format)
{
return ParseExact(data, format, false);
}
public static string[] ParseExact(
this string data,
string format,
bool ignoreCase)
{
string[] values;
if (TryParseExact(data, format, out values, ignoreCase))
return values;
else
throw new ArgumentException("Format not compatible with value.");
}
public static bool TryExtract(
this string data,
string format,
out string[] values)
{
return TryParseExact(data, format, out values, false);
}
public static bool TryParseExact(
this string data,
string format,
out string[] values,
bool ignoreCase)
{
int tokenCount = 0;
format = Regex.Escape(format).Replace("\\{", "{");
for (tokenCount = 0; ; tokenCount++)
{
string token = string.Format("{{{0}}}", tokenCount);
if (!format.Contains(token)) break;
format = format.Replace(token,
string.Format("(?'group{0}'.*)", tokenCount));
}
RegexOptions options =
ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;
Match match = new Regex(format, options).Match(data);
if (tokenCount != (match.Groups.Count - 1))
{
values = new string[] { };
return false;
}
else
{
values = new string[tokenCount];
for (int index = 0; index < tokenCount; index++)
values[index] =
match.Groups[string.Format("group{0}", index)].Value;
return true;
}
}
}
フォーマットされていない文字列はどのくらいの期間ですか? –
@Chris:妥当な範囲内です。 ATM、私はファイル名にしか使用していません。 –
一般に、結果はあいまいかもしれないことに注意してください。 'format = '{0} - {1}''と 'arr = {" as-df "、" qw-er "}'です。 3つの異なる方法でフォーマット解除することができます。あいまいさに対処する方法を定義するか、書式文字列の内容と値を制限する必要があります。 – peterchen