RegEx.Matchesを使用して、一致する値を異なる(アルファベット順)順序で検索して書き戻す方法はありますか?
今のところ私は次のようなものを持っています:
var pattern = @"(KEY `[\w]+?` \(`.*`*\))";
var keys = Regex.Matches(line, pattern);
Console.WriteLine("\n\n");
foreach (Match match in keys)
{
Console.WriteLine(match.Index + " = " + match.Value.Replace("\n", "").Trim());
}
しかし、私が本当に必要としているのは、table.sqlダンプを取得し、既存のINDEXESをアルファベット順に並べ替えることです。サンプルコードは次のとおりです。
line = "...PRIMARY KEY (`communication_auto`),\n KEY `idx_current` (`current`),\n KEY `idx_communication` (`communication_id`,`current`),\n KEY `idx_volunteer` (`volunteer_id`,`current`),\n KEY `idx_template` (`template_id`,`current`)\n);"
ありがとうJ
更新: ありがとう、m.buettnerソリューションは私が先に進むために使用できる基本を私に与えました。悲しいことに、私は正規表現があまり得意ではありませんが、それでも改善できると信じているコードになってしまいました。
...
//sort INDEXES definitions alphabetically
if (line.Contains(" KEY `")) line = Regex.Replace(
line,
@"[ ]+(KEY `[\w]+` \([\w`,]+\),?\s*)+",
ReplaceCallbackLinq
);
static string ReplaceCallbackLinq(Match match)
{
var result = String.Join(",\n ",
from Capture item in match.Groups[1].Captures
orderby item.Value.Trim()
select item.Value.Trim().Replace("),", ")")
);
return " " + result + "\n";
}
更新: インデックスフィールドが255文字より長い場合もあります。mysqlはインデックスを255までトリミングし、次のように書き込みます。
KEY `idx3` (`app_property_definition_id`,`value`(255),`audit_current`),
したがって、このケースにも一致させるために、いくつかのコードを変更する必要がありました:ReplaceCallbackLinq:
select item.Value.Trim().Replace("`),", "`)")
および正規表現の定義:
@"[ ]+(KEY `[\w]+` \([\w`(\(255\)),]+\),?\s*)+",