是否有任何方式使用RegEx.Matches來查找並回寫匹配值,但以不同(按字母順序)的順序?C#排序並放回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轉儲和按字母順序排列現有的索引,例如代碼:
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);"
感謝 Ĵ
更新: 謝謝,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`),
如此,爲了配合得這種情況下,我不得不改變一些代碼: 在ReplaceCall backLinq:
select item.Value.Trim().Replace("`),", "`)")
和正則表達式定義:
@"[ ]+(KEY `[\w]+` \([\w`(\(255\)),]+\),?\s*)+",
謝謝,這個解決方案給了我可以繼續使用的基礎知識。可悲的是,我並不擅長RegEx,但我最終得到的代碼相信還可以改進: –