に変換するために私が知っている唯一の組み込みメソッドPascalCase
はTextInfo.ToTitleCase
であり、設計上、すべて大文字の単語を処理しません。これを回避するために、すべての単語部分を検出できるカスタム正規表現を作成し、それらを個別にタイトル/パスカル ケースに変換します。
string ToPascalCase(string s)
{
// Find word parts using the following rules:
// 1. all lowercase starting at the beginning is a word
// 2. all caps is a word.
// 3. first letter caps, followed by all lowercase is a word
// 4. the entire string must decompose into words according to 1,2,3.
// Note that 2&3 together ensure MPSUser is parsed as "MPS" + "User".
var m = Regex.Match(s, "^(?<word>^[a-z]+|[A-Z]+|[A-Z][a-z]+)+$");
var g = m.Groups["word"];
// Take each word and convert individually to TitleCase
// to generate the final output. Note the use of ToLower
// before ToTitleCase because all caps is treated as an abbreviation.
var t = Thread.CurrentThread.CurrentCulture.TextInfo;
var sb = new StringBuilder();
foreach (var c in g.Captures.Cast<Capture>())
sb.Append(t.ToTitleCase(c.Value.ToLower()));
return sb.ToString();
}
この関数は、一般的なユース ケースを処理する必要があります。
s | ToPascalCase(s)
MPSUser | MpsUser
ArticleID | ArticleId
closeMethod | CloseMethod